From 218db1a8473957357a06dd27d24fc813abb9daa6 Mon Sep 17 00:00:00 2001
From: Azarias Boutin
Date: Thu, 13 Jun 2019 15:30:05 +0200
Subject: [PATCH 001/919] Missing console.log
Question is "what's the output" but console.log is not called
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 035ce096..8f5a893b 100644
--- a/README.md
+++ b/README.md
@@ -804,7 +804,7 @@ String.prototype.giveLydiaPizza = () => {
const name = "Lydia";
-name.giveLydiaPizza();
+console.log(name.giveLydiaPizza());
```
- A: `"Just give Lydia pizza already!"`
From 8d4a71711f4bdcd60b874d3bdb4a303f2aee13ec Mon Sep 17 00:00:00 2001
From: Azarias Boutin
Date: Thu, 13 Jun 2019 15:34:42 +0200
Subject: [PATCH 002/919] Update README.md
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 8f5a893b..5b742ac1 100644
--- a/README.md
+++ b/README.md
@@ -1006,7 +1006,7 @@ function sayHi() {
return (() => 0)();
}
-typeof sayHi();
+console.log(typeof sayHi());
```
- A: `"object"`
From e9fa9d7812f235d93f884397aa5718f172d0f86d Mon Sep 17 00:00:00 2001
From: Patrix252
Date: Sun, 16 Jun 2019 16:19:44 +0200
Subject: [PATCH 003/919] Fix the question 21
The output is `undefined` because it is an assignment, then we have to ask for the value of the `sum` const.
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 0becf81f..f4fbb874 100644
--- a/README.md
+++ b/README.md
@@ -627,7 +627,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa
---
-###### 21. What's the output?
+###### 21. What's value of `sum`?
```javascript
const sum = eval("10*10+5");
From 8af62dd6021aa1f3406016fb96f4b35a529fc02a Mon Sep 17 00:00:00 2001
From: Joel
Date: Sun, 16 Jun 2019 22:01:07 +0100
Subject: [PATCH 004/919] Fixing typo
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 7ac6e6c4..834bae2c 100644
--- a/README.md
+++ b/README.md
@@ -229,7 +229,7 @@ console.log(b === c);
`new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object.
-When we use the `==` operator, it only checks whether it has the same _value_. They do they both have the value of `3`, so it returns `true`.
+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.`
From b0d906d95d439aaaa2c3a2d003923cc3a86cc12c Mon Sep 17 00:00:00 2001
From: Brandon Phillips
Date: Sun, 16 Jun 2019 17:31:41 -0600
Subject: [PATCH 005/919] Clarify Question 39
I think it's helpful to describe what a primitive is and how they're different from objects as well as describing why, in practice, primitive values can behave like objects. Otherwise the answer feels pretty abstract.
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 7ac6e6c4..abdbc7c2 100644
--- a/README.md
+++ b/README.md
@@ -1180,6 +1180,8 @@ 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.
+
From d2224eaaf12616ca3e304c3c57d9f0a542a5c29f Mon Sep 17 00:00:00 2001
From: Seonggwon Yoon
Date: Mon, 17 Jun 2019 18:42:40 +0900
Subject: [PATCH 008/919] Fix typo
Signed-off-by: Seonggwon Yoon
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 2e06edad..ad45ee46 100644
--- a/README.md
+++ b/README.md
@@ -461,7 +461,7 @@ sum(1, "2");
#### Answer: C
-JavaScript is a **dynamimcally typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another.
+JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another.
In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`.
From 7254980188e4daa911d9000238c1f98bea1f5d9a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com>
Date: Mon, 17 Jun 2019 16:45:34 +0200
Subject: [PATCH 009/919] Add list of languages
---
README.md | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index ad45ee46..f5bb6259 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,10 @@ From basic to advanced: test how well you know JavaScript, refresh your knowledg
The answers are in the collapsed sections below the questions, simply click on them to expand it. Good luck :heart:
-[中文版本](./README-zh_CN.md)
+---
+List of a available languages:
+* 🇨🇳[中文版本](./README-zh_CN.md)
+* 🇪🇸[Versión en español](./README-ES.md)
---
From 4f22f11bdbeeb86c3995070ba83e788750067e84 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adri=C3=A1n?= <22575055+aguadotzn@users.noreply.github.com>
Date: Mon, 17 Jun 2019 17:01:33 +0200
Subject: [PATCH 010/919] First commit
---
README-ES.md | 1296 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 1296 insertions(+)
create mode 100644 README-ES.md
diff --git a/README-ES.md b/README-ES.md
new file mode 100644
index 00000000..391673e1
--- /dev/null
+++ b/README-ES.md
@@ -0,0 +1,1296 @@
+
+# Lista de preguntas (avanzadas) de JavaScript
+
+ Publico diariamente preguntas de opción múltiple en JavaScript en mi [Instagram](https://www.instagram.com/theavocoder), que también publicaré aquí!
+
+ Desde lo básico a lo avanzado: comprueba si realmente conoces _Javascript_, actualiza tus conocimientos o simplemente prepárate para tu próxima entrevista 💪
+
+ Actualizaré este repo semanalmente con nuevas preguntas. Las respuestas se encuentran en las secciones contraídas debajo de las preguntas, simplemente haz clic en ellas para expandirlas. Buena suerte ❤️
+
+---
+Lista de lenguajes disponibles:
+* 🇬🇧[English version](./README.md)
+* 🇨🇳[中文版本](./README-zh_CN.md)
+
+
+---
+
+###### 1. ¿Qué devuelve la siguiente función?
+
+```javascript
+function sayHi() {
+ console.log(name);
+ console.log(age);
+ var name = "Lydia";
+ let age = 21;
+}
+
+sayHi();
+```
+
+- A: `Lydia` y `undefined`
+- B: `Lydia` y `ReferenceError`
+- C: `ReferenceError` y `21`
+- D: `undefined` y `ReferenceError`
+
+Answer
+
+
+#### Respuesta: D
+
+Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`.
+
+Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`.
+
+
+
+
+---
+
+###### 2. ¿Qué devuelve la siguiente función?
+
+```javascript
+for (var i = 0; i < 3; i++) {
+ setTimeout(() => console.log(i), 1);
+}
+
+for (let i = 0; i < 3; i++) {
+ setTimeout(() => console.log(i), 1);
+}
+```
+
+- A: `0 1 2` and `0 1 2`
+- B: `0 1 2` and `3 3 3`
+- C: `3 3 3` and `0 1 2`
+
+Answer
+
+
+#### Respuesta: C
+
+Because of the event queue in JavaScript, the `setTimeout` function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` function was invoked, `i` was equal to `3` in the first example.
+
+In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop.
+
+
+
+#### Answer: B
+
+Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function.
+
+With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example).
+
+There is no value `radius` on that object, which returns `undefined`.
+
+
+
+
+---
+
+###### 4. What's the output?
+
+```javascript
++true;
+!"Lydia";
+```
+
+- A: `1` and `false`
+- B: `false` and `NaN`
+- C: `false` and `false`
+
+Answer
+
+
+#### Answer: A
+
+The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`.
+
+The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`.
+
+
+
+
+---
+
+###### 5. Which one is NOT valid?
+
+```javascript
+const bird = {
+ size: "small"
+};
+
+const mouse = {
+ name: "Mickey",
+ small: true
+};
+```
+
+- A: `mouse.bird.size`
+- B: `mouse[bird.size]`
+- C: `mouse[bird["size"]]`
+- D: All of them are valid
+
+Answer
+
+
+#### Answer: A
+
+In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood.
+
+JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement.
+
+`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true`
+
+However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`.
+
+
+
+#### 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.
+
+
+
+#### 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.`
+
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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!
+
+
+
+#### 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.
+
+
+
+#### 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"`.
+
+
+
+#### 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`.
+
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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`.
+
+
+
+#### 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.
+
+
+
+#### 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!
+
+
+
+#### 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`.
+
+
+
+#### 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
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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.)
+
+
+
+#### 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.
+
+
+
+#### 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]`
+
+
+
+#### 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.
+
+
+
+#### Answer: A
+
+A string is an iterable. The spread operator maps every character of an iterable to one element.
+
+
+
From d2596b731aa51356463757ae78974064997e4551 Mon Sep 17 00:00:00 2001
From: karataev
Date: Tue, 18 Jun 2019 12:49:53 +0700
Subject: [PATCH 011/919] Translate questions 1-10 to russian
---
README_ru-RU.md | 1293 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 1293 insertions(+)
create mode 100644 README_ru-RU.md
diff --git a/README_ru-RU.md b/README_ru-RU.md
new file mode 100644
index 00000000..131f2099
--- /dev/null
+++ b/README_ru-RU.md
@@ -0,0 +1,1293 @@
+# Список (продвинутых) вопросов по JavaScript
+
+Я ежедевно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории.
+
+От азов к сложным вопросам: провеь как хорошо ты знаешь JavaScript, освежи свои знания или приготовься к собеседованию! :muscle: :rocket: Я дополняю этот репозиторий каждую неделю новыми вопросами.
+
+Ответы находятся в свернутой секции ниже вопросов. Просто нажми на ответ, чтобы развернуть. Удачи! :heart:
+
+[中文版本](./README-zh_CN.md)
+[Русский](./README_ru-RU.md)
+
+---
+
+###### 1. Что будет в консоли?
+
+```javascript
+function sayHi() {
+ console.log(name);
+ console.log(age);
+ var name = "Lydia";
+ let age = 21;
+}
+
+sayHi();
+```
+
+- A: `Lydia` и `undefined`
+- B: `Lydia` и `ReferenceError`
+- C: `ReferenceError` и `21`
+- D: `undefined` и `ReferenceError`
+
+Ответ
+
+
+#### Ответ: D
+
+Внутри функции мы сперва определям переменную `name` с помощью ключевого слова `var`. Это означает, что переменная будет поднята (область памяти под переменную будет выделена во время фазы создания) со значением `undefined` по умолчанию, до тех пора пока исполнение кода не дойдет до строчки, где определяется переменная. Мы еще не определили значение `name` когда пытаемся вывести её в консоль, поэтому в консоли будет `undefined`.
+
+Переменные, определенные с помощью `let` (и `const`), также поднимаются, но в отличие от `var`, не инициализируются. Доступ к ним не возможен до тех пор, пока не выполнится строка их определения (инициализации). Это называется "временная мертвая зона". Когда мы пытаемся обратиться к переменным до того момента как они определены, JavaScript выбрасывает исключение `ReferenceError`.
+
+
+
+
+---
+
+###### 2. Что будет в консоли?
+
+```javascript
+for (var i = 0; i < 3; i++) {
+ setTimeout(() => console.log(i), 1);
+}
+
+for (let i = 0; i < 3; i++) {
+ setTimeout(() => console.log(i), 1);
+}
+```
+
+- A: `0 1 2` и `0 1 2`
+- B: `0 1 2` и `3 3 3`
+- C: `3 3 3` и `0 1 2`
+
+Ответ
+
+
+#### Ответ: C
+
+Из-за очереди событий в JavaScript, функция `setTimeout` вызывается _после_ того как цикл будет завершен. Так как переменная `i` в первом цикле была определена с помощью `var`, она будет глобальной. В цикле мы каждый раз увеличиваем значение `i` на `1`, используя унарный оператор `++`. К моменту выполнения функции `setTimeout` значение `i` будет равно `3` в первом примере.
+
+Во втором цикле переменная `i` определена с помощью `let`. Такие переменные (а также `const`) имеют блочную область видимости (блок это что угодно между `{ }`). С каждой итерацией `i` будет иметь новое значение, и каждое значение будет замкнуто в своей области видимости внутри цикла.
+
+
+
+
+---
+
+###### 3. Что будет в консоли?
+
+```javascript
+const shape = {
+ radius: 10,
+ diameter() {
+ return this.radius * 2;
+ },
+ perimeter: () => 2 * Math.PI * this.radius
+};
+
+shape.diameter();
+shape.perimeter();
+```
+
+- A: `20` и `62.83185307179586`
+- B: `20` и `NaN`
+- C: `20` и `63`
+- D: `NaN` и `63`
+
+Ответ
+
+
+#### Ответ: B
+
+Заметь, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция.
+
+У стрелочных функций значение `this` указывает на окружающую область видимости, в отличие от обычных функций! Это значит, что при вызове `perimeter` значение `this` у этой функции указывает не на объект `shape`, а на внешнюю область видимости (например, window).
+
+У этого объекта нет ключа `radius`, поэтому возвращается `undefined`.
+
+
+
+
+---
+
+###### 4. Что будет в консоли?
+
+```javascript
++true;
+!"Lydia";
+```
+
+- A: `1` и `false`
+- B: `false` и `NaN`
+- C: `false` и `false`
+
+Ответ
+
+
+#### Ответ: A
+
+Унарный плюс приводит операнд к числу. `true` это `1`, а `false` это `0`.
+
+Строка `'Lydia'` это "истинное" значение. На самом деле мы спрашиваем "является ли это истинное значение ложным"? Ответ: `false`.
+
+
+
+#### Ответ: A
+
+В JavaScript все ключи объекта являются строками (кроме Symbol). И хотя мы не _набираем_ их как строки, они всегда преобразовываются к строкам под капотом.
+
+JavaScript интерпретирует (или распаковывает) операторы. При использовании квадратных скобок JS замечает `[` и продолжает пока не встретит `]`. Только после этого он вычислит то, что находится внутри скобок.
+
+`mouse[bird.size]`: Сперва определяется `bird.size`, которое равно `"small"`. `mouse["small"]` возвращает `true`.
+
+Но с записью через точку так не происходит. У `mouse` нет ключа `bird`. Таким образом, `mouse.bird` равно `undefined`. Затем мы запрашиваем ключ `size`, используя точечную нотацию: `mouse.bird.size`. Так как `mouse.bird` это `undefined`, мы запрашиваем `undefined.size`. Это не является валидным, и мы получаем ошибку типа `Cannot read property "size" of undefined`.
+
+
+
+#### Ответ: 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`.
+
+
+
+#### Ответ: D
+
+Функция `colorChange` является статичной. Статичные методы не имеют доступа к экземплярам класса. Так как `freddie` это экземпляр, то статичный метод там не доступен. Поэтому выбрасывается ошибка `TypeError`.
+
+
+
+
+---
+
+###### 9. Что будет в консоли?
+
+```javascript
+let greeting;
+greetign = {}; // Опечатка!
+console.log(greetign);
+```
+
+- A: `{}`
+- B: `ReferenceError: greetign is not defined`
+- C: `undefined`
+
+Ответ
+
+
+#### Ответ: A
+
+В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле выполнил `global.greetign = {}` (или `window.greetign = {}` в браузере).
+
+Нужно использовать `"use strict"`, чтобы избежать такого поведения. Эта запись поможет быть уверенным в том, что переменная была определена перед тем как ей присвоили значение.
+
+
+
+
+---
+
+###### 10. Что произойдет?
+
+```javascript
+function bark() {
+ console.log("Woof!");
+}
+
+bark.animal = "dog";
+```
+
+- A: Ничего, всё в порядке!
+- B: `SyntaxError`. Нельзя добавлять свойства функциям таким способом.
+- C: `undefined`
+- D: `ReferenceError`
+
+Ответ
+
+
+#### Ответ: A
+
+В JavaScript это возможно, т.к. функции это объекты! (Всё есть объект кроме примитивов).
+
+Функция это специальный тип объекта, который можно вызвать. Функция это объект со свойствами.
+A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable.
+
+
+
+#### 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!
+
+
+
+#### 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.
+
+
+
+#### 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"`.
+
+
+
+#### 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`.
+
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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`.
+
+
+
+#### 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.
+
+
+
+#### 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!
+
+
+
+#### 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`.
+
+
+
+#### 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
+
+
+#### 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.
+
+
+
+#### 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.
+
+
+
+#### 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.)
+
+
+
+#### 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.
+
+
+
+#### 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]`
+
+
+
+#### 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.
+
+
+
+#### Answer: A
+
+A string is an iterable. The spread operator maps every character of an iterable to one element.
+
+
+
From a992034bb7f1c14b79cce55422133ba28fab6b92 Mon Sep 17 00:00:00 2001
From: karataev
Date: Tue, 18 Jun 2019 14:02:06 +0700
Subject: [PATCH 012/919] Translate questions 11-20 to russian
---
README_ru-RU.md | 134 ++++++++++++++++++++++++------------------------
1 file changed, 67 insertions(+), 67 deletions(-)
diff --git a/README_ru-RU.md b/README_ru-RU.md
index 131f2099..a462ecb0 100644
--- a/README_ru-RU.md
+++ b/README_ru-RU.md
@@ -330,7 +330,7 @@ A function is a special type of object. The code you write yourself isn't the ac
---
-###### 11. What's the output?
+###### 11. Что будет в консоли?
```javascript
function Person(firstName, lastName) {
@@ -351,12 +351,12 @@ console.log(member.getFullName());
- C: `Lydia Hallie`
- D: `undefined` `undefined`
-Answer
+Ответ
-#### Answer: A
+#### Ответ: A
-You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case,
+Нельзя добавлять свойства конструктору, как обычному объекту. Если нужно добавить фичу всем объектам, то необходимо использовать прототипы. В данном случае
```js
Person.prototype.getFullName = function () {
@@ -364,14 +364,14 @@ Person.prototype.getFullName = function () {
}
```
-would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it!
+сделает метод `member.getFullName()` рабочим. В чем тут преимущество? Предположим, что мы добавили этот метод к конструктору. Возможно, не каждому экземпляру `Person` нужен этот метод. Это приведет к большим потерям памяти, т.к. все экземпляры будут иметь это свойство. Напротив, если мы добавим этот метод только к прототипу, у нас будет только одно место в памяти, к которому смогут обращаться все экземпляры!
---
-###### 12. What's the output?
+###### 12. Что будет в консоли?
```javascript
function Person(firstName, lastName) {
@@ -386,38 +386,38 @@ console.log(lydia);
console.log(sarah);
```
-- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined`
-- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}`
-- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}`
-- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError`
+- A: `Person {firstName: "Lydia", lastName: "Hallie"}` и `undefined`
+- B: `Person {firstName: "Lydia", lastName: "Hallie"}` и `Person {firstName: "Sarah", lastName: "Smith"}`
+- C: `Person {firstName: "Lydia", lastName: "Hallie"}` и `{}`
+- D:`Person {firstName: "Lydia", lastName: "Hallie"}` и `ReferenceError`
-Answer
+Ответ
-#### Answer: A
+#### Ответ: A
-For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**!
+Для `sarah` мы не использовали ключевое слово `new`. Использование `new` приводит к созданию нового объекта. Но без `new` он указывает на **глобальный объект**!
-We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`.
+Мы указали, что `this.firstName` равно `"Sarah"` и `this.lastName` равно `"Smith"`. На самом деле мы определили `global.firstName = 'Sarah'` и `global.lastName = 'Smith'`. `sarah` осталась `undefined`.
---
-###### 13. What are the three phases of event propagation?
+###### 13. Назовите три фазы распространения событий
-- A: Target > Capturing > Bubbling
-- B: Bubbling > Target > Capturing
-- C: Target > Bubbling > Capturing
-- D: Capturing > Target > Bubbling
+- A: Цель > Захват > Всплытие
+- B: Всплытие > Цель > Захват
+- C: Цель > Всплытие > Захват
+- D: Захват > Цель > Всплытие
-Answer
+Ответ
-#### Answer: D
+#### Ответ: D
-During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins.
+Во время фазы **захвата** событие распространяется с элементов родителей до элемента цели. После достижения **цели** начинается фаза **всплытия**.
@@ -426,24 +426,24 @@ During the **capturing** phase, the event goes through the ancestor elements dow
---
-###### 14. All object have prototypes.
+###### 14. Все объекты имют прототипы
-- A: true
-- B: false
+- A: Да
+- B: Нет
-Answer
+Ответ
-#### Answer: B
+#### Ответ: B
-All objects have prototypes, except for the **base object**. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you.
+Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект имеет доступ до некоторых методов и свойств, таких как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет.
---
-###### 15. What's the output?
+###### 15. Каким будет результат?
```javascript
function sum(a, b) {
@@ -458,21 +458,21 @@ sum(1, "2");
- C: `"12"`
- D: `3`
-Answer
+Ответ
-#### Answer: C
+#### Ответ: C
-JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another.
+JavaScript это **динамически типизированный язык**: мы не определяем тип переменных. Переменные могут автоматически быть преобразованы из одного типа в другой без нашего участия, что называется _неявным приведением типов_. **Приведение** это преобразование из одного типа в другой.
-In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`.
+В этом примере JavaScript сконвертировал число `1` в строку, чтобы операция внутри функции имела смысл и вернула значение. Во время сложения числа (`1`) и строки (`'2'`) число преобразовывается к строке. Мы можем конкатенировать строки вот так: `"Hello" + "World"`. Таким образом, `"1" + "2"` возвращает `"12"`.
---
-###### 16. What's the output?
+###### 16. Что будет в консоли?
```javascript
let number = 0;
@@ -486,29 +486,29 @@ console.log(number);
- C: `0` `2` `2`
- D: `0` `1` `2`
-Answer
+Ответ
-#### Answer: C
+#### Ответ: C
-The **postfix** unary operator `++`:
+**Постфиксный** унарный оператор `++`:
-1. Returns the value (this returns `0`)
-2. Increments the value (number is now `1`)
+1. Возвращает значение (`0`)
+2. Инкрементирует значение (теперь число равно `1`)
-The **prefix** unary operator `++`:
+**Префиксный** унарный оператор `++`:
-1. Increments the value (number is now `2`)
-2. Returns the value (this returns `2`)
+1. Инкрементирует значение (число теперь равно `2`)
+2. Возвращает значение (`2`)
-This returns `0 2 2`.
+Результат: `0 2 2`.
---
-###### 17. What's the output?
+###### 17. Что будет в консоли?
```javascript
function getPersonInfo(one, two, three) {
@@ -527,55 +527,55 @@ getPersonInfo`${person} is ${age} years old`;
- B: `["", " is ", " years old"]` `"Lydia"` `21`
- C: `"Lydia"` `["", " is ", " years old"]` `21`
-Answer
+Ответ
-#### Answer: B
+#### Ответ: B
-If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions!
+При использовании тегированных шаблонных литералов первым аргументом всегда будет массив строковых значений. Оставшимися аргументами будут значения переданных выражений!
---
-###### 18. What's the output?
+###### 18. Что будет в консоли?
```javascript
function checkAge(data) {
if (data === { age: 18 }) {
- console.log("You are an adult!");
+ console.log("Ты взрослый!");
} else if (data == { age: 18 }) {
- console.log("You are still an adult.");
+ console.log("Ты все еще взрослый.");
} else {
- console.log(`Hmm.. You don't have an age I guess`);
+ console.log(`Хмм.. Кажется, у тебя нет возраста.`);
}
}
checkAge({ age: 18 });
```
-- A: `You are an adult!`
-- B: `You are still an adult.`
-- C: `Hmm.. You don't have an age I guess`
+- A: `Ты взрослый!`
+- B: `Ты все еще взрослый.`
+- C: `Хмм.. Кажется, у тебя нет возраста.`
-Answer
+Ответ
-#### Answer: C
+#### Ответ: C
-When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory.
+В операциях сравнения примитивы сравниваются по их _значениям_, а объекты по _ссылкам_. JavaScript проверяет, чтобы объекты указывали на одну и ту же область памяти.
-The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality.
+Сравниваемые объекты в нашем примере не такие: объект, переданный в качестве параметра, указывает на другую область памяти, чем объекты, используемые в сравнениях.
-This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`.
+Поэтому `{ age: 18 } === { age: 18 }` и `{ age: 18 } == { age: 18 }` возвращают `false`.
---
-###### 19. What's the output?
+###### 19. Что будет в консоли?
```javascript
function getAge(...args) {
@@ -590,19 +590,19 @@ getAge(21);
- C: `"object"`
- D: `"NaN"`
-Answer
+Ответ
-#### Answer: C
+#### Ответ: C
-The spread operator (`...args`.) returns an array with arguments. An array is an object, so `typeof args` returns `"object"`
+Оператор распространения (`...args`) возвращает массив с аргументами. Массив это объект, поэтому `typeof args` возвращает `"object"`.
---
-###### 20. What's the output?
+###### 20. Что будет в консоли?
```javascript
function getAge() {
@@ -619,12 +619,12 @@ getAge();
- C: `ReferenceError`
- D: `TypeError`
-Answer
+Ответ
-#### Answer: C
+#### Ответ: C
-With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object.
+Используя `"use strict"`, можно быть уверенным, что мы по ошибке не побъявим глобальные переменные. Мы ранее нигде не объявляли переменную `age`, поэтому с использованием `"use strict"` возникнет `ReferenceError`. Без использования `"use strict"` ошибки не возникнет, а переменная `age` добавится в глобальный объект.
From a5fc8a389513a6745114965cbb004cf1984223f1 Mon Sep 17 00:00:00 2001
From: Lydia
Date: Tue, 18 Jun 2019 09:04:56 +0200
Subject: [PATCH 013/919] 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 014/919] 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 015/919] 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 016/919] 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 017/919] 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`, т.к. у них блочная область видимости.
-#### 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`.
-#### 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`.
-#### 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`.
-#### 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 018/919] =?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
+Ответ
---
-###### 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
+Ответ
---
-###### 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.
+Строка является итерируемой сущностью. Оператор распространения преобразовывает каждый символ в отдельный элемент.
-#### 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 020/919] 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 021/919] 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.
-
-#### 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`.
-
-#### 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"
-
-#### 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`.
-
-#### 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.
-
-#### 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 "`.
-
-#### 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`.
-
-#### 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 '.
-
-#### 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 '`
-
-#### 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.
-
-#### 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.
-
-#### 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`.
-
-#### 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!
-
-#### 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`.
-
-#### 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
-