diff --git a/README.md b/README.md index ab549280..b203a060 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,50 @@
- +

JavaScript Questions

+
---- +> [!NOTE] +> This repo was created in 2019 and the questions provided here are therefore based on the JavaScript syntax and behavior at that time. Since JavaScript is a constantly evolving language, there are newer language features that are not covered by the questions here. +--- -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th +

+From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:

-From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart:
+

Feel free to reach out to me! 😊

-Feel free to reach out to me! 😊
-Instagram || Twitter || LinkedIn || Blog - +

+ Instagram || Twitter || LinkedIn || Blog +

---- +| Feel free to use them in a project! 😃 I would _really_ appreciate a reference to this repo, I create the questions and explanations (yes I'm sad lol) and the community helps me so much to maintain and improve it! 💪🏼 Thank you and have fun! | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -
See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰

-* [English](./en-EN/README.md) -* [العربية](./ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](./ar-EG/README_ar-EG.md) -* [Bosanski](./bs-BS/README-bs_BS.md) -* [Deutsch](./de-DE/README.md) -* [Español](./es-ES/README-ES.md) -* [Français](./fr-FR/README_fr-FR.md) -* [日本語](./ja-JA/README-ja_JA.md) -* [한국어](./ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](./pt-BR/README_pt_BR.md) -* [Русский](./ru-RU/README.md) -* [Українська мова](./ua-UA/README-ua_UA.md) -* [Tiếng Việt](./vi-VI/README-vi.md) -* [中文版本](./zh-CN/README-zh_CN.md) -* [Türkçe](./tr-TR/README-tr_TR.md) -* [ไทย](./th-TH/README-th_TH.md) -* [Indonesia](./id-ID/README.md) +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](./ro-RO/README.ro.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md)

@@ -133,7 +142,7 @@ Note that the value of `diameter` is a regular function, whereas the value of `p With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example). -There is no value `radius` on that object, which returns `undefined`. +Since there is no value `radius` in the scope of the arrow function, `this.radius` returns `undefined` which, when multiplied by `2 * Math.PI`, results in `NaN`.

@@ -158,7 +167,7 @@ There is no value `radius` on that object, which returns `undefined`. The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +The string `'Lydia'` is a truthy value. What we're actually asking, is "Is this truthy value falsy?". This returns `false`.

@@ -260,9 +269,9 @@ console.log(b === c); `new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. -When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. +When we use the `==` operator (Equality operator), it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. -However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.` +However, when we use the `===` operator (Strict equality operator), both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.`

@@ -297,7 +306,7 @@ console.log(freddie.colorChange('orange')); #### Answer: D -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since `freddie` is a child, the function is not passed down, and not available on the `freddie` instance: a `TypeError` is thrown. +The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children or called upon class instances. Since `freddie` is an instance of class Chameleon, the function cannot be called upon it. A `TypeError` is thrown.

@@ -321,7 +330,12 @@ console.log(greetign); #### Answer: A -It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as `global.greetign = {}` (or `window.greetign = {}` in a browser). +It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as: + +1. `global.greetign = {}` in Node.js +2. `window.greetign = {}`, `frames.greetign = {}` and `self.greetign` in browsers. +3. `self.greetign` in web workers. +4. `globalThis.greetign` in all environments. In order to avoid this, we can use `"use strict"`. This makes sure that you have declared a variable before setting it equal to anything. @@ -385,7 +399,9 @@ console.log(member.getFullName()); #### Answer: A -You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case, +In JavaScript, functions are objects, and therefore, the method `getFullName` gets added to the constructor function object itself. For that reason, we can call `Person.getFullName()`, but `member.getFullName` throws a `TypeError`. + +If you want a method to be available to all object instances, you have to add it to the prototype property: ```js Person.prototype.getFullName = function() { @@ -393,8 +409,6 @@ 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! -

@@ -418,14 +432,14 @@ console.log(sarah); - A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` - B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` - C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError`
Answer

#### Answer: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +For `sarah`, we didn't use the `new` keyword. When using `new`, `this` refers to the new empty object we create. However, if you don't add `new`, `this` refers to the **global object**! We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. @@ -624,7 +638,7 @@ getAge(21); #### Answer: C -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` +The rest parameter (`...args`) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"`

@@ -660,7 +674,7 @@ With `"use strict"`, you can make sure that you don't accidentally declare globa --- -###### 21. What's value of `sum`? +###### 21. What's the value of `sum`? ```javascript const sum = eval('10*10+5'); @@ -676,7 +690,7 @@ const sum = eval('10*10+5'); #### Answer: A -`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. +`eval` evaluates code that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`.

@@ -729,7 +743,7 @@ console.log(num); With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. -You cannot do this with `let` or `const` since they're block-scoped. +You cannot do this with `let` or `const` since they're block-scoped and therefore can't be redeclared.

@@ -844,7 +858,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -857,7 +871,7 @@ name.giveLydiaPizza(); #### Answer: A -`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! +`String` is a built-in constructor, that we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method!

@@ -889,9 +903,9 @@ console.log(a[b]); Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`. -However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["object Object"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["object Object"] = 456`. +However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["[object Object]"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["[object Object]"] = 456`. -Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to `456`, so it returns `456`. +Then, we log `a[b]`, which is actually `a["[object Object]"]`. We just set that to `456`, so it returns `456`.

@@ -1000,7 +1014,7 @@ The deepest nested element that caused the event is the target of the event. You #### Answer: A -If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards. +If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, targeting, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards.

@@ -1059,9 +1073,9 @@ console.log(typeof sayHi()); #### Answer: B -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. - -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"`. +The `sayHi` function returns the returned value of the immediately invoked function expression (IIFE). This function returned `0`, which is type `"number"`. + +FYI: `typeof` can return the following list of values: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` and `object`. Note that `typeof null` returns `"object"`.

@@ -1089,14 +1103,16 @@ undefined; #### Answer: A -There are only six falsy values: +There are 8 falsy values: - `undefined` - `null` - `NaN` -- `0` -- `''` (empty string) - `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) Function constructors, like `new Number` and `new Boolean` are truthy. @@ -1137,9 +1153,9 @@ numbers[10] = 11; console.log(numbers); ``` -- A: `[1, 2, 3, 7 x null, 11]` +- A: `[1, 2, 3, null x 7, 11]` - B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` +- C: `[1, 2, 3, empty x 7, 11]` - D: `SyntaxError`
Answer @@ -1149,7 +1165,7 @@ console.log(numbers); When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: -`[1, 2, 3, 7 x empty, 11]` +`[1, 2, 3, empty x 7, 11]` depending on where you run it (it's different for every browser, node, etc.) @@ -1211,7 +1227,7 @@ JavaScript only has primitive types and objects. Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. -What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the object using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour. +What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the primitive type using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behavior.

@@ -1501,7 +1517,7 @@ const num = parseInt('7*6', 10); #### Answer: C -Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. +Only the first number in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. `*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. @@ -1510,7 +1526,7 @@ Only the first numbers in the string is returned. Based on the _radix_ (the seco --- -###### 50. What's the output`? +###### 50. What's the output? ```javascript [1, 2, 3].map(num => { @@ -1604,9 +1620,9 @@ sayHi(); #### Answer: D -With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world'`. +With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world!'`. -With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world'`. +With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world!'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world!'`.

@@ -1635,7 +1651,9 @@ console.log(myCar.make); #### Answer: B -When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`. +When a constructor function is called with the `new` keyword, it creates an object and sets the `this` keyword to refer to that object. By default, if the constructor function doesn't explicitly return anything, it will return the newly created object. + +In this case, the constructor function `Car` explicitly returns a new object with `make` set to `"Maserati"`, which overrides the default behavior. Therefore, when `new Car()` is called, the _returned_ object is assigned to `myCar`, resulting in the output being `"Maserati"` when `myCar.make` is accessed.

@@ -1663,16 +1681,16 @@ console.log(typeof y); #### Answer: A -`let x = y = 10;` is actually shorthand for: +`let x = (y = 10);` is actually shorthand for: ```javascript y = 10; let x = y; ``` -When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`. +When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in the browser, `global` in Node). In a browser, `window.y` is now equal to `10`. -Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately-invoked function (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. +Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately invoked function expression (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, and holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`. @@ -1805,7 +1823,7 @@ console.log(delete age); #### Answer: A -The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator. +The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const`, or `let` keywords cannot be deleted using the `delete` operator. The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`. @@ -1971,9 +1989,9 @@ console.log(num2); #### Answer: A -The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. +The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterward. -`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. +`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`). Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`.

@@ -2040,7 +2058,7 @@ In this example, we are not returning any values, we are simply logging the valu The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged. +On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator, and the current values: `1` and `2` get logged. If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged. @@ -2128,9 +2146,9 @@ export const sum = (a, b) => a + b; #### Answer: B -With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. +With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, and the code in the file that imports the module gets executed _after_. -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. +This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we had used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console.

@@ -2218,7 +2236,7 @@ With the `+` operator, you can concatenate strings. In this case, we are concate function* startGame() { const answer = yield 'Do you love JavaScript?'; if (answer !== 'Yes') { - return "Oh wow... Guess we're gone here"; + return "Oh wow... Guess we're done here"; } return 'JavaScript loves you back ❤️'; } @@ -2373,7 +2391,7 @@ console.log(shape); `Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). -When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` returns true, since the variable `shape` has a reference to a frozen object. +When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` would return true, since the variable `shape` has a reference to a frozen object. Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged. @@ -2385,9 +2403,9 @@ Since `shape` is frozen, and since the value of `x` is not an object, we cannot ###### 76. What's the output? ```javascript -const { name: myName } = { name: 'Lydia' }; +const { firstName: myName } = { firstName: 'Lydia' }; -console.log(name); +console.log(firstName); ``` - A: `"Lydia"` @@ -2400,11 +2418,45 @@ console.log(name); #### Answer: D -When we unpack the property `name` from the object on the right-hand side, we assign its value `"Lydia"` to a variable with the name `myName`. +By using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax we can unpack values from arrays, or properties from objects, into distinct variables: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// ES5 version: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Also, a property can be unpacked from an object and assigned to a variable with a different name than the object property: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// ES5 version: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Therefore, `firstName` does not exist as a variable, thus attempting to access its value will raise a `ReferenceError`. + +**Note:** Be aware of the `global scope` properties: + +```javascript +const { name: myName } = { name: 'Lydia' }; -With `{ name: myName }`, we tell JavaScript that we want to create a new variable called `myName` with the value of the `name` property on the right-hand side. +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser e.g. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` -Since we try to log `name`, a variable that is not defined, a ReferenceError gets thrown. +Whenever Javascript is unable to find a variable within the _current scope_, it climbs up the [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) and searches for it and if it reaches the top-level scope, aka **Global scope**, and still doesn't find it, it will throw a `ReferenceError`. + +- In **Browsers** such as _Chrome_, `name` is a _deprecated global scope property_. In this example, the code is running inside _global scope_ and there is no user-defined local variable for `name`, therefore it searches the predefined _variables/properties_ in the global scope which is in the case of browsers, it searches through `window` object and it will extract the [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) value which is equal to an **empty string**. + +- In **NodeJS**, there is no such property on the `global` object, thus attempting to access a non-existent variable will raise a [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined).

@@ -2470,7 +2522,7 @@ console.log(addFunction(5 * 2)); The `add` function is a _memoized_ function. With memoization, we can cache the results of a function in order to speed up its execution. In this case, we create a `cache` object that stores the previously returned values. -If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the caches value will be returned, which saves on execution time. Else, if it's not cached, it will calculate the value and store it afterwards. +If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the cache value will be returned, which saves execution time. Otherwise, if it's not cached, it will calculate the value and store it afterward. We call the `addFunction` function three times with the same value: on the first invocation, the value of the function when `num` is equal to `10` isn't cached yet. The condition of the if-statement `num in cache` returns `false`, and the else block gets executed: `Calculated! 20` gets logged, and the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. @@ -2681,7 +2733,7 @@ console.log(checkAge(21)); #### Answer: C -Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown. +Variables with the `const` and `let` keywords are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown.

@@ -2731,7 +2783,7 @@ function getName(name) { #### Answer: A -With `!!name`, we determine whether the value of `name` is truthy or falsy. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. +With `!!name`, we determine whether the value of `name` is truthy or falsy. If the name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. @@ -2760,9 +2812,9 @@ console.log('I want pizza'[0]); #### Answer: B -In order to get an character on a specific index in a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case we want to get the element which index is 0, the character `"I'`, which gets logged. +In order to get a character at a specific index of a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case, we want to get the element with index 0, the character `"I'`, which gets logged. -Note that this method is not supported in IE7 and below. In that case, use `.charAt()` +Note that this method is not supported in IE7 and below. In that case, use `.charAt()`.

@@ -2791,7 +2843,7 @@ sum(10); You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. +If you're trying to set a default parameter's value equal to a parameter that is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error.

@@ -2821,7 +2873,7 @@ console.log(data); #### Answer: A -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. +With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function that returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. @@ -2856,7 +2908,7 @@ console.log(typeof member); Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: ```javascript -function Person() { +function Person(name) { this.name = name; } ``` @@ -3006,7 +3058,7 @@ The above example works. This returns the array `[ 'banana', 'apple', 'orange', function nums(a, b) { if (a > b) console.log('a is bigger'); else console.log('b is bigger'); - return; + return a + b; } @@ -3119,7 +3171,7 @@ console.log(getList(list)) console.log(getUser(user)) ``` -- A: `[1, [2, 3, 4]]` and `undefined` +- A: `[1, [2, 3, 4]]` and `SyntaxError` - B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` - C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` - D: `Error` and `{ name: "Lydia", age: 21 }` @@ -3135,11 +3187,11 @@ The `getList` function receives an array as its argument. Between the parenthese With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: +The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to instantly return an _object_ from an arrow function, you have to write it between parentheses, otherwise everything between the two braces will be interpreted as a block statement. In this case the code between the braces is not a valid JavaScript code, so a `SyntaxError` gets thrown. -`const getUser = user => ({ name: user.name, age: user.age })` +The following function would have returned an object: -Since no value gets returned in this case, the function returns `undefined`. +`const getUser = user => ({ name: user.name, age: user.age })`

@@ -3164,7 +3216,7 @@ console.log(name()); #### Answer: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +The variable `name` holds the value of a string, which is not a function, and thus cannot be invoked. TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! @@ -3268,7 +3320,7 @@ secondFunction(); With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. +We can get this value with both `.then` and the `await` keywords in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. @@ -3326,7 +3378,7 @@ Promise.resolve(5); - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Answer @@ -3334,7 +3386,7 @@ Promise.resolve(5); #### Answer: C -We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value. If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. +We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. @@ -3493,7 +3545,7 @@ console.log(food); #### Answer: A -We set the value of the `favoriteFood` property on the `info` object equal to the string with the pizza emoji, `'🍕'`. A string is a primitive data type. In JavaScript, primitive data types act by reference +We set the value of the `favoriteFood` property on the `info` object equal to the string with the pizza emoji, `'🍕'`. A string is a primitive data type. In JavaScript, primitive data types don't interact by reference. In JavaScript, primitive data types (everything that's not an object) interact by _value_. In this case, we set the value of the `favoriteFood` property on the `info` object equal to the value of the first element in the `food` array, the string with the pizza emoji in this case (`'🍕'`). A string is a primitive data type, and interact by value (see my [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) if you're interested in learning more) @@ -3681,7 +3733,11 @@ config = null; #### Answer: C -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. As long as there is a reference, the object won't get garbage collected. Since it's not garbage collected, the `setInterval` callback function will still get invoked every 1000ms (1s). +Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. +As long as there is a reference, the object won't get garbage collected. +Since this is an interval, setting `config` to `null` or `delete`-ing `config.alert` won't garbage-collect the interval, so the interval will still be called. +It should be cleared with `clearInterval(config.alert)` to remove it from memory. +Since it was not cleared, the `setInterval` callback function will still get invoked every 1000ms (1s).

@@ -3717,7 +3773,7 @@ myMap.get(() => 'greeting'); When adding a key/value pair using the `set` method, the key will be the value of the first argument passed to the `set` function, and the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, and the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. 1 is wrong, since the key is not `'greeting'` but `() => 'greeting'`. -3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory. +3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interacts by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory.

@@ -3809,7 +3865,7 @@ console.log(list[(num += 1)]); #### Answer: B -With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰. +With the `+=` operator, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰.

@@ -3838,7 +3894,7 @@ console.log(member.getLastName?.()); ``` - A: `undefined` `undefined` `undefined` `undefined` -- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` - C: `Mara` `null` `Lydia Hallie` `null` - D: `null` `ReferenceError` `null` `ReferenceError` @@ -3852,7 +3908,7 @@ With the optional chaining operator `?.`, we no longer have to explicitly check `person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. `person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. `person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`member.getLastName?.()`: variable `member` is non-existent therefore a `ReferenceError` gets thrown!

@@ -4001,7 +4057,7 @@ async function* range(start, end) { #### Answer: C -The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promsie, the resolved _values_ of the promises get returned: `1`, `2`, then `3`. +The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promise, the resolved _values_ of the promises get returned: `1`, `2`, then `3`.

@@ -4039,17 +4095,17 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ - 'en-US', - { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); - const formattedAmount = new Intl.NumberFormat({ - 'en-US', - { style: 'currency', currency: 'USD' } - }).format(amount) + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; } console.log(getFine(130, 300)) @@ -4065,7 +4121,7 @@ console.log(getFine(130, 300)) #### Answer: B -With the `Intl.NumberFormat` method, we can format numeric values to any locale. We format the numeric value `130` to the `en-US` locale as a `unit` in `mile-per-hour`, which results in `130 mph`. The numeric value `300` to the `en-US` locale as a `currentcy` in `USD` results in `$300.00`. +With the `Intl.NumberFormat` method, we can format numeric values to any locale. We format the numeric value `130` to the `en-US` locale as a `unit` in `mile-per-hour`, which results in `130 mph`. The numeric value `300` to the `en-US` locale as a `currency` in `USD` results in `$300.00`.

@@ -4153,7 +4209,7 @@ getInfo(); #### Answer: D -Variables declared with the `const` keyword are not referencable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function. +Variables declared with the `const` keyword are not referenceable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function.

@@ -4257,7 +4313,7 @@ console.log(counterOne.count); Then, we create a new variable `counterTwo`, and set it equal to `counterOne`. Since objects interact by reference, we're just creating a new reference to the same spot in memory that `counterOne` points to. Since it has the same spot in memory, any changes made to the object that `counterTwo` has a reference to, also apply to `counterOne`. Currently, `counterTwo.count` is `2`. -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. +We invoke `counterTwo.increment()`, which sets `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. @@ -4269,51 +4325,55 @@ We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we ###### 133. What's the output? ```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); +const myPromise = Promise.resolve(Promise.resolve('Promise')); function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); } async function funcTwo() { const res = await myPromise; - console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); } funcOne(); funcTwo(); ``` -- A: `Promise! Last line! Promise! Last line! Last line! Promise!` -- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` -- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` -- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!`
Answer

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

--- -###### 134. How can we invoke `sum` in `index.js` from `sum.js?` +###### 134. How can we invoke `sum` in `sum.js` from `index.js?` ```javascript // sum.js @@ -4395,13 +4455,13 @@ person.name; #### Answer: C -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis case, we pass the `handler` object which contained to properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. +With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In this case, we pass the `handler` object which contains two properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, and `get` gets invoked whenever we _get_ (access) property values. The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. -Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. +Then, we access a property value on the proxy object, and the `get` property on the handler object is invoked. `"Accessed a property!"` gets logged.

@@ -4426,7 +4486,7 @@ Object.seal(person); #### Answer: A -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. +With `Object.seal` we can prevent new properties from being _added_, or existing properties to be _removed_. However, you can still modify the value of existing properties. @@ -4490,7 +4550,7 @@ myFunc(3); #### Answer: A -First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. +First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` is the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argument `num`. We didn't pass an argument for `value`. Since we didn't pass a value for the `value` argument, it got the default value: the returned value of the `add` function. To `add`, we pass `num`, which has the value of `3`. `add` returns `6`, which is the value of `value`. @@ -4530,7 +4590,7 @@ console.log(counter.#number) #### Answer: D -In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot acccess it outside the `Counter` class! +In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot access it outside the `Counter` class!

@@ -4613,11 +4673,11 @@ console.log(person.hobbies); The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `y`, `"running"` gets added to this empty array. +First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. -Last, we invoke the `addHobby` function, and pass `"bdaking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. +Last, we invoke the `addHobby` function, and pass `"baking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` @@ -4655,7 +4715,7 @@ const pet = new Flamingo(); #### Answer: B -We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. THe constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`. +We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. The constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`.

@@ -4683,7 +4743,7 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; #### Answer: D -The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The properties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0.

@@ -4718,7 +4778,7 @@ Objects aren't iterable by default. An iterable is an iterable if the iterator p --- -###### 146. What's the output? +###### 145. What's the output? ```javascript let count = 0; @@ -4748,7 +4808,7 @@ The `if` condition within the `forEach` loop checks whether the value of `num` i --- -###### 147. What's the output? +###### 146. What's the output? ```javascript function getFruit(fruits) { @@ -4772,7 +4832,7 @@ getFruit([['🍍'], ['🍊', '🍌']]) The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. -First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. +First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. @@ -4783,7 +4843,7 @@ Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray o --- -###### 148. What's the output? +###### 147. What's the output? ```javascript class Calc { @@ -4792,7 +4852,7 @@ class Calc { } increase() { - this.count ++ + this.count++ } } @@ -4819,7 +4879,7 @@ We set the variable `calc` equal to a new instance of the `Calc` class. Then, we --- -###### 149. What's the output? +###### 148. What's the output? ```javascript const user = { @@ -4861,7 +4921,7 @@ The `updateUser` function updates the values of the `email` and `password` prope --- -###### 150. What's the output? +###### 149. What's the output? ```javascript const fruit = ['🍌', '🍊', '🍎'] @@ -4869,6 +4929,8 @@ const fruit = ['🍌', '🍊', '🍎'] fruit.slice(0, 1) fruit.splice(0, 1) fruit.unshift('🍇') + +console.log(fruit) ``` - A: `['🍌', '🍊', '🍎']` @@ -4890,7 +4952,7 @@ At last, we invoke the `unshift` method on the `fruit` array, which modifies the --- -###### 151. What's the output? +###### 150. What's the output? ```javascript const animals = {}; @@ -4915,18 +4977,18 @@ console.log(animals[dog]) Object keys are converted to strings. -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. +Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"[object Object]"` equal to the new object. `animals["[object Object]"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. +`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals["[object Object]"]` with the new cat properties. -Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. +Logging `animals[dog]`, or actually `animals["[object Object]"]` since converting the `dog` object to a string results `"[object Object]"`, returns the `{ emoji: "🐈", name: "Sara" }`.

--- -###### 152. What's the output? +###### 151. What's the output? ```javascript const user = { @@ -4957,7 +5019,7 @@ The `updateEmail` function is an arrow function, and is not bound to the `user` --- -###### 153. What's the output? +###### 152. What's the output? ```javascript const promise1 = Promise.resolve('First') @@ -4986,7 +5048,104 @@ runPromises() #### Answer: D -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects) with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. +The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects_ with the value of the rejected promise. In this case, `promise3` is rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` is rejected with this value. + +

+ + +--- + +###### 153. What should the value of `method` be to log `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Answer +

+ +#### Answer: C + +The `fromEntries` method turns a 2d array into an object. The first element in each subarray will be the key, and the second element in each subarray will be the value. In this case, we’re mapping over the `keys` array, which returns an array that the first element is the item on the key array on the current index, and the second element is the item of the values array on the current index. + +This creates an array of subarrays containing the correct keys and values, which results in `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. What's the output? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Answer +

+ +#### Answer: C + +The default value of `address` is an empty object `{}`. When we set the variable `member` equal to the object returned by the `createMember` function, we didn't pass a value for the address, which means that the value of the address is the default empty object `{}`. An empty object is a truthy value, which means that the condition of the `address ? address : null` conditional returns `true`. The value of the address is the empty object `{}`. + +

+
+ +--- + +###### 155. What's the output? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Answer +

+ +#### Answer: B + +The condition within the `if` statement checks whether the value of `!typeof randomValue` is equal to `"string"`. The `!` operator converts the value to a boolean value. If the value is truthy, the returned value will be `false`, if the value is falsy, the returned value will be `true`. In this case, the returned value of `typeof randomValue` is the truthy value `"number"`, meaning that the value of `!typeof randomValue` is the boolean value `false`. + +`!typeof randomValue === "string"` always returns false, since we're actually checking `false === "string"`. Since the condition returned `false`, the code block of the `else` statement gets run, and `Yay it's a string!` gets logged.

-
\ No newline at end of file + diff --git a/ar-AR/README_AR.md b/ar-AR/README_AR.md index 8b33a246..ace6ed98 100644 --- a/ar-AR/README_AR.md +++ b/ar-AR/README_AR.md @@ -14,23 +14,28 @@ اللغات المتوفرة: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) ____________ @@ -61,8 +66,9 @@ sayHi(); الإجابة هي الخيار الرابع : D في داخل الدالة, قمنا أولا بتعريف المتغير `name` مع الكلمة المفتاحية `var`. و هذا يعني ان المتغير قد حصلت له عملية hoisting والتي تعني انه قد تم حجز مساحة لهذا المتغير في هذه اللحظة مع قيمة مبدئية و التي هي `undefined` إلى ان نقوم فعليا بتعريف قيمة له لاحقا. -لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. -المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `var`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`. +لم نقم بتعريف المتغير `name` بعد عندما قمنا بطباعته في السطر الاول من الدالة, لهذا لايزال يحمل القيمة `undefined`. +
+المتغيرات التي تم تعريفها بجانب الكلمات المفتاحية `let` و `const` يتم عمل عملية hoisting لها أيضا, ولكن على عكس المتغيرات التي يتم تعريفها بجانب الكلمة المفتاحية `var`, لا يتم تعريفها او الوصول اليها مالم نقم بإضافة قيمة لها فعليا. و يسمى هذا بال"temporal dead zone".عندما نحاول الوصول الى المتغيرات من النوع `let`قبل ان يتم تعريفها, نتحصل على الخطأ التالي `ReferenceError`.

@@ -866,7 +872,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1088,7 +1094,7 @@ console.log(typeof sayHi()); دالة `sayHi` تقوم بإرجاع القيمة المرجعة من الدالة المناداة في اللحظة (IIFE). هذه الدالة تقوم بإرجاع `0`, و الذي نوعه عبارة عن `"number"`. -لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`. +لمعلوماتك: لدينا فقط سبعة أنواع من ال built-in و هي : `null`, `undefined`, `boolean`, `number`, `string`, `object`, و `symbol`, و `bigint`.`"function"` هي ليست نوع, وبما أن الدوال عبارة عن objects, ف هي ليست من النوع `"object"`.

diff --git a/ar-EG/README_ar-EG.md b/ar-EG/README_ar-EG.md index 656a2ccf..b9024d95 100644 --- a/ar-EG/README_ar-EG.md +++ b/ar-EG/README_ar-EG.md @@ -891,7 +891,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` diff --git a/bs-BS/README-bs_BS.md b/bs-BS/README-bs_BS.md index e040e6cb..33f0384f 100644 --- a/bs-BS/README-bs_BS.md +++ b/bs-BS/README-bs_BS.md @@ -5,30 +5,35 @@ Svakodnevno postavljam JavaScript pitanja s višestrukim izborom na moj [Instagram](https://www.instagram.com/theavocoder), koja također objavljujem ovdje! -Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, osvježite svoj -znanje malo, ili pripremiti za svoj intervju! :muscle: :rocket: +Od osnovnog do naprednog: testirajte koliko dobro znate JavaScript, malo osvježite +svoje znanje, ili se pripremite za svoj intervju! :muscle: :rocket: Ovaj tjedni repo ažuriram s novim pitanjima. Odgovori su jednostavno dijelovima ispod pitanja kliknite na njih da biste ih proširili. Sretno :heart: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) * * * * * @@ -63,10 +68,10 @@ još nismo definirali varijablu na liniji gdje pokušavamo prijaviti varijabla `name`, tako da još uvijek sadrži vrijednost` undefined`. Varijable s ključnom riječi `let` (i` const`) su podignute, ali za razliku od njih -`var`, ne bivaju inicijalizirane . Nisu dostupni prije -linije na kojo ih proglašavamo (inicijaliziramo). To se naziva "temporal dead zone". +`var`, ne bivaju inicijalizirane . Nisu dostupne prije +linije na kojoj ih proglašavamo (inicijaliziramo). To se naziva "temporal dead zone". Kada pokušamo pristupiti varijablama prije nego što budu deklarirane, -JavaScript iz bacuje `ReferenceError`. +JavaScript izbacuje `ReferenceError`.

@@ -179,7 +184,7 @@ Niz '' Lydia '' je istinita vrijednost. Ono što zapravo tražimo jest * * * * * -###### 5. Koja je istina? +###### 5. Što je od ovoga istina? ```javascript const bird = { @@ -207,9 +212,9 @@ iako ih možda ne * upisujemo kao * nizove, oni se uvijek pretvaraju u String ispod "haube". JavaScript tumači (ili odlaže) izjave. Kada koristimo zagradu -notacija, on vidi prvu otvarnu zagradu ```i nastavlja dalje do nje +notacija, on vidi prvu otvorenu zagradu ```i nastavlja dalje do nje pronalazi završnu zagradu `]`. Tek tada će procijeniti -izjava. +izjavu. `mouse [bird.size]`: Prvo procjenjuje `bird.size`, što je` `small``. `mouse [" small "]` vraća "true" @@ -249,7 +254,7 @@ console.log(d.greeting); #### Odgovor: A -U JavaScriptu, svi objekti međusobno djeluju * referencom * kada ih postavljaju +U JavaScriptu, svi objekti međusobno djeluju *referencom* kada ih postavljaju jednaki. Prvo, varijabla `c` sadrži vrijednost objekta. Kasnije dodijelimo `d` @@ -286,15 +291,15 @@ console.log(b === c); #### Odgovor: C -`new Number ()` je ugrađeni konstruktor function. Iako izgleda +`new Number ()` je ugrađena konstruktor funkcija. Iako izgleda kao broj, to zapravo nije broj: ima gomilu ekstra dodataka pa je zbog toga objekt. -Kada koristimo `==` operatora, on samo provjerava ima li isti +Kada koristimo `==` operator, on samo provjerava ima li isti *vrijednost*. Obje imaju vrijednost `3`, pa se vraća 'true'. Međutim, kada koristimo `===` operator, obje vrijednosti * i * trebaju biti -isto. To nije: `new Number ()` nije broj, to je ** objekt **. +iste. To nije: `new Number ()` nije broj, to je ** objekt **. Oba vraćaju "false"

@@ -372,7 +377,7 @@ da ste deklarirali varijablu prije nego je postavite na bilo što. * * * * * -###### 10. Što se događa kada to učinimo? +###### 10. Što se događa kada učinimo ovo? ```javascript function bark() { @@ -392,12 +397,12 @@ bark.animal = "dog"; #### Odgovor: A -To je moguće u JavaScriptu, jer su funkcije objekti! +Ovo je moguće u JavaScriptu, jer su funkcije objekti! (Sve osim primitivnih tipova su objekti) function je posebna vrsta objekta. Kod koji sami napišete -nije stvarna function. function je objekt sa svojstvima. -Ova nekretnina je nepovratna. +nije stvarna funkcija. Function je objekt sa svojstvima. +To svojstvo je nepovratno.

@@ -431,7 +436,7 @@ console.log(member.getFullName()); #### Odgovor: A Ne možete dodati svojstva konstruktoru kao što možete s uobičajenim -objekti. Ako želite dodati značajku svim objektima odjednom, imate +objektima. Ako želite dodati značajku svim objektima odjednom, imate umjesto toga koristiti prototip. Dakle, u ovom slučaju, ```{.js} @@ -440,12 +445,12 @@ Person.prototype.getFullName = function () { }; ``` -bi učinio `member.getFullName ()`. Zašto je to korisno? Reći će mo +bi učinio `member.getFullName ()`. Zašto je to korisno? Reći ćemo da smo tu metodu dodali samom konstruktoru. Možda ne svaki Primjer "Person" trebao je ovu metodu. To bi trošilo puno memorije scopa (prostora), jer bi oni još uvijek imali tu svojinu, koja uzima memoriju scopa za svaku instancu. Umjesto toga, ako ga samo dodamo prototipu, mi -će mo je imati na jednom mjestu u memoriji, ali svi imaju pristup! +ćemo je imati na jednom mjestu u memoriji, ali svi imaju pristup!

@@ -479,8 +484,8 @@ console.log(sarah); #### Odgovor: A -Za `sarah` nismo koristili ključnu riječ` new`. Kada koristite "new", to -odnosi se na new prazni objekt koji stvaramo. Međutim, ako ne dodate +Za `Sarah` nismo koristili ključnu riječ` new`. Kada koristite "new", to +odnosi se na novi prazni objekt koji stvaramo. Međutim, ako ne dodate `new` se odnosi na ** globalni objekt **! Rekli smo da je "this.ime" jednako "Sarah" i `this.prezime` @@ -944,7 +949,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `` Već daj Lizijinu pizzu! `` diff --git a/de-DE/README.md b/de-DE/README.md index a8e775de..0ac8c271 100644 --- a/de-DE/README.md +++ b/de-DE/README.md @@ -1,33 +1,56 @@ -# JavaScript Fragen (für Fortgeschrittene) +
+ +

JavaScript Fragen (für Fortgeschrittene)

-Täglich poste ich mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentlichen werde. +--- + +Ich veröffentliche jeden Tag mehrere Multiple-Choice-Fragen über JavaScript auf meinem [Instagram-Account](https://www.instagram.com/theavocoder), die ich nun auch hier veröffentliche. + +Von einfach bis fortgeschritten: teste, wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo regelmäßig mit neuen Fragen erweitern. Die Antworten sind unterhalb der Fragen **versteckt**. Du kannst einfach darauf klicken, um die Antworten anzuzeigen. Viel Glück :heart: + +Kontaktiert mich, wenn ihr möchtet! 😊
+Instagram || Twitter || LinkedIn || Blog +
+ +| Benutzt die Fragen und Lösungen in einem Projekt! 😃 Ich würde mich _sehr_ freuen, wenn ihr dieses Repo verlinkt. Ich erstelle die Fragen und antworten (ja, ich bin traurig, lol) und die Community hilft mir unglaublich dabei, das ganze zu pflegen und verbessern! 💪🏼 Danke und habt Spaß! | +|---| -Von einfach bis fortgeschritten: teste wie gut du JavaScript kennst, frische dein Wissen auf oder bereite dich auf ein Vorstellungsgespräch vor! :muscle: :rocket: Ich werde dieses Repo wöchentlich mit neuen Fragen erweitern. + + +--- + +
Alle 20 Übersetzungen anzeigen 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

-Die Antworten sind unterhalb der Fragen versteckt. Du kannst einfach darauf klicken um die Antworten anzuzeigen. Viel Glück :heart: +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) -### Alle verfügbaren Sprachen -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +

+
--- -###### 1. Was ist der Output? +###### 1. Was wird ausgegeben? ```javascript function sayHi() { @@ -59,7 +82,7 @@ Variablen mit dem `let` (oder `const`) Keyword werden ebenfalls gehoisted, aber --- -###### 2. Was ist der Output? +###### 2. Was wird ausgegeben? ```javascript for (var i = 0; i < 3; i++) { @@ -89,7 +112,7 @@ In der zweiten Schleife wurde die Variable `i` mit dem `let` Keyword definiert: --- -###### 3. Was ist der Output? +###### 3. Was wird ausgegeben? ```javascript const shape = { @@ -125,7 +148,7 @@ Es gibt keinen Wert `radius` in dem Object, daher wird `undefined` zurückgegebe --- -###### 4. Was ist der Output? +###### 4. Was wird ausgegeben? ```javascript +true; @@ -186,7 +209,7 @@ Mit der Dot Notation ist das nicht der Fall. `mouse` hat keinen Key namens `bird --- -###### 6. Was ist der Output? +###### 6. Was wird ausgegeben? ```javascript let c = { greeting: "Hey!" }; @@ -221,7 +244,7 @@ Wenn ein Object geändert wird, werden alle Referenzen zu diesem Object ebenfall --- -###### 7. Was ist der Output? +###### 7. Was wird ausgegeben? ```javascript let a = 3; @@ -254,7 +277,7 @@ Wenn wir aber `===` nutzen müssen sowohl der Wert _als auch_ der Typ übereinst --- -###### 8. Was ist der Output? +###### 8. Was wird ausgegeben? ```javascript class Chameleon { @@ -289,7 +312,7 @@ Die `colorChange` Funktion ist statisch (`static`). Statische Methoden existiere --- -###### 9. Was ist der Output? +###### 9. Was wird ausgegeben? ```javascript let greeting; @@ -344,7 +367,7 @@ Eine Funktion ist ein spezieller Typ eines Objekts. Der Code, den wir schreiben --- -###### 11. Was ist der Output? +###### 11. Was wird ausgegeben? ```javascript function Person(firstName, lastName) { @@ -386,7 +409,7 @@ Stattdessen haben wir sie nur dem Prototype zugewiesen, sodass sie nur an einer --- -###### 12. Was ist der Output? +###### 12. Was wird ausgegeben? ```javascript function Person(firstName, lastName) { @@ -458,7 +481,7 @@ Alle Objekte haben Prototypes, außer dem **Basis Objekt**. Das Basis Objekt hat --- -###### 15. Was ist der Output? +###### 15. Was wird ausgegeben? ```javascript function sum(a, b) { @@ -487,7 +510,7 @@ In diesem Beispiel wandelt JavaScript die Nummer `1` in einem String um, sodass --- -###### 16. Was ist der Output? +###### 16. Was wird ausgegeben? ```javascript let number = 0; @@ -523,7 +546,7 @@ Der Output ist daher `0 2 2`. --- -###### 17. Was ist der Output? +###### 17. Was wird ausgegeben? ```javascript function getPersonInfo(one, two, three) { @@ -554,7 +577,7 @@ Wenn man Template Literals verwendet ist das erste Argument immer ein Array der --- -###### 18. Was ist der Output? +###### 18. Was wird ausgegeben? ```javascript function checkAge(data) { @@ -590,7 +613,7 @@ Deshalb werfen sowohl `{ age: 18 } === { age: 18 }` als auch `{ age: 18 } == { a --- -###### 19. Was ist der Output? +###### 19. Was wird ausgegeben? ```javascript function getAge(...args) { @@ -617,7 +640,7 @@ Der Spread Operator (`...args`) gibt ein Array mit Argumenten zurück. Ein Array --- -###### 20. Was ist der Output? +###### 20. Was wird ausgegeben? ```javascript function getAge() { @@ -694,7 +717,7 @@ Wenn man stattdessen `localStorage` verwendet, bleibt der Wert für immer besteh --- -###### 23. Was ist der Output? +###### 23. Was wird ausgegeben? ```javascript var num = 8; @@ -722,7 +745,7 @@ Das ist nicht möglich mit `let` oder `const`, da diese dem Block Scope unterlie --- -###### 24. Was ist der Output? +###### 24. Was wird ausgegeben? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -753,7 +776,7 @@ Das funktioniert nicht für Set. Da wir keine `'1'` in unserem Set haben wirft ` --- -###### 25. Was ist der Output? +###### 25. Was wird ausgegeben? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -795,7 +818,7 @@ Der Base Execution Context entspricht dem Global Execution Context und ist über --- -###### 27. Was ist der Output? +###### 27. Was wird ausgegeben? ```javascript for (let i = 1; i < 5; i++) { @@ -821,7 +844,7 @@ for (let i = 1; i < 5; i++) { --- -###### 28. Was ist der Output? +###### 28. Was wird ausgegeben? ```javascript String.prototype.giveLydiaPizza = () => { @@ -830,7 +853,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -850,7 +873,7 @@ name.giveLydiaPizza(); --- -###### 29. Was ist der Output? +###### 29. Was wird ausgegeben? ```javascript const a = {}; @@ -884,7 +907,7 @@ Dann loggen wir `a[b]`, was eigentlich `a["object Object"]` ist und gerade von u --- -###### 30. Was ist der Output? +###### 30. Was wird ausgegeben? ```javascript const foo = () => console.log("First"); @@ -993,7 +1016,7 @@ Wenn wir auf den Paragraph klicken, sehen wir zwei logs: `p` und `div`. Während --- -###### 33. Was ist der Output? +###### 33. Was wird ausgegeben? ```javascript const person = { name: "Lydia" }; @@ -1025,7 +1048,7 @@ In beiden Fällen können wir das Objekt weiter reichen, auf welches sich das `t --- -###### 34. Was ist der Output? +###### 34. Was wird ausgegeben? ```javascript function sayHi() { @@ -1047,7 +1070,7 @@ typeof sayHi(); Die `sayHi` Funktion gibt den Wert der sofort ausgeführten Funktion (IIFE) zurück. Die Funktion gibt `0` zurück, was vom Typ `"number"` ist. -Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `number`, `string`, `object`, und `symbol`. `"function"` ist kein Typ, weil Funktionen Objekte sind und daher dem Typ `"object"` entsprechen. +Es gibt nur 7 eingebaute Typen in JavaScript: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, und `bigint`. `"function"` ist kein Typ, weil Funktionen Objekte sind und daher dem Typ `"object"` entsprechen.

@@ -1091,7 +1114,7 @@ Funktions-Constructor, wie `new Number` und `new Boolean` sind truthy. --- -###### 36. Was ist der Output? +###### 36. Was wird ausgegeben? ```javascript console.log(typeof typeof 1); @@ -1115,7 +1138,7 @@ console.log(typeof typeof 1); --- -###### 37. Was ist der Output? +###### 37. Was wird ausgegeben? ```javascript const numbers = [1, 2, 3]; @@ -1144,7 +1167,7 @@ abhängig davon wo das Array ausgeführt wird (die Ausgabe ist unterschiedlich f --- -###### 38. Was ist der Output? +###### 38. Was wird ausgegeben? ```javascript (() => { @@ -1204,7 +1227,7 @@ Was einen primitiven Typ von einem Objekt unterscheidet ist, dass Primitive kein --- -###### 40. Was ist der Output? +###### 40. Was wird ausgegeben? ```javascript [[0, 1], [2, 3]].reduce( @@ -1234,7 +1257,7 @@ Dann entspricht `acc` gleich `[1, 2, 0, 1]` und `cur` ist gleich `[2, 3]`. Wir v --- -###### 41. Was ist der Output? +###### 41. Was wird ausgegeben? ```javascript !!null; @@ -1309,7 +1332,7 @@ Ein String ist ein Iterable. Der Spread Operator mappt jedes Zeichen eines Itera --- -###### 44. Was ist der Output? +###### 44. Was wird ausgegeben? ```javascript function* generator(i) { @@ -1375,7 +1398,7 @@ Wenn wir mehrere Promises in die `Promice.race` Methode eingegeben, wird das Pro --- -###### 46. Was ist der Output? +###### 46. Was wird ausgegeben? ```javascript let person = { name: "Lydia" }; @@ -1414,7 +1437,7 @@ Wir ändern nur den Wert der Variable `person` und nicht das erste Element im Ar --- -###### 47. Was ist der Output? +###### 47. Was wird ausgegeben? ```javascript const person = { @@ -1444,7 +1467,7 @@ Mit einer `for-in` Schleife können wir über Objekt Keys iterieren - in diesem --- -###### 48. Was ist der Output? +###### 48. Was wird ausgegeben? ```javascript console.log(3 + 4 + "5"); @@ -1496,7 +1519,7 @@ Nur die erste Zahl im String wird ausgegeben. Aufgrund des _radix_ (das zweite A --- -###### 50. Was ist der Output? +###### 50. Was wird ausgegeben? ```javascript [1, 2, 3].map(num => { @@ -1524,7 +1547,7 @@ Allerdings geben wir keinen Wert aus. Wenn unsere Funktion keinen Wert ausgibt, --- -###### 51. Was ist der Output? +###### 51. Was wird ausgegeben? ```javascript function getInfo(member, year) { @@ -1561,7 +1584,7 @@ Der Wert von `person` ist ein Objekt, sodass das Argument `member` eine Kopie de --- -###### 52. Was ist der Output? +###### 52. Was wird ausgegeben? ```javascript function greeting() { @@ -1599,7 +1622,7 @@ Mit dem `catch` Statement können wir definieren, was passiert, wenn die Excepti --- -###### 53. Was ist der Output? +###### 53. Was wird ausgegeben? ```javascript function Car() { @@ -1628,7 +1651,7 @@ Wenn man eine Property ausgibt ist der Wert der Property gleich dem ausgegeben W --- -###### 54. Was ist der Output? +###### 54. Was wird ausgegeben? ```javascript (() => { @@ -1668,7 +1691,7 @@ Da wir die Variable `y` aber global erstellt haben ist ihr Wert `10` auch hier v --- -###### 55. Was ist der Output? +###### 55. Was wird ausgegeben? ```javascript class Dog { @@ -1709,7 +1732,7 @@ Wenn wir versuchen etwas auszuführen, was keine Funktion ist, wird ein `TypeErr --- -###### 56. Was ist der Output? +###### 56. Was wird ausgegeben? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1736,7 +1759,7 @@ Wir übergeben `[1, 1, 2, 3, 4]` mit einer doppelten `1`. Da wir keine doppelten --- -###### 57. Was ist der Output? +###### 57. Was wird ausgegeben? ```javascript // counter.js @@ -1772,7 +1795,7 @@ Wenn wir also den Wert von `myCounter` erhöhen bekommen wir den Fehler `myCount --- -###### 58. Was ist der Output? +###### 58. Was wird ausgegeben? ```javascript const name = "Lydia"; @@ -1801,7 +1824,7 @@ Der Wert von `name` wurde mit `const` deklariert, weshalb `delete` nicht möglic --- -###### 59. Was ist der Output? +###### 59. Was wird ausgegeben? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1843,7 +1866,7 @@ Das bedeutet, dass der Wert von `y` gleich des ersten Wertes im Array ist, spric --- -###### 60. Was ist der Output? +###### 60. Was wird ausgegeben? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1869,7 +1892,7 @@ Es ist möglich Objekte mit dem Spread Operator `...` zu verbinden. Dieser erste --- -###### 61. Was ist der Output? +###### 61. Was wird ausgegeben? ```javascript const person = { name: "Lydia" }; @@ -1899,7 +1922,7 @@ Properties, die mit `defineProperty` erstellt wurden sind standardmäßig unver --- -###### 62. Was ist der Output? +###### 62. Was wird ausgegeben? ```javascript const settings = { @@ -1933,7 +1956,7 @@ Wenn der Replacer eine _Funktion_ ist, so wird diese Funktion für jede Property --- -###### 63. Was ist der Output? +###### 63. Was wird ausgegeben? ```javascript let num = 10; @@ -1969,7 +1992,7 @@ Der unäre Operator `++` _gibt zuerst_ den Wert des Operanden aus und _erhöht d --- -###### 64. Was ist der Output? +###### 64. Was wird ausgegeben? ```javascript const value = { number: 10 }; @@ -2007,7 +2030,7 @@ Beim vierten Mal übergeben wir wieder eine `value`. `x.number` wurde zuvor in ` --- -###### 65. Was ist der Output? +###### 65. Was wird ausgegeben? ```javascript [1, 2, 3, 4].reduce((x, y) => console.log(x, y)); @@ -2036,7 +2059,7 @@ Wenn wir keinen Wert einer Funktion ausgeben wird `undefined` ausgegeben. Beim n Beim vierten Call geben wir wieder nichts aus, sodass der Akkumulator wieder `undefined` ist und der aktuelle Wert `4`. `undefined` und `4` werden geloggt.

- + --- ###### 66. Mit welchem Constructor können wir die `Dog` Klasse erweitern? @@ -2049,7 +2072,7 @@ class Dog { }; class Labrador extends Dog { - // 1 + // 1 constructor(name, size) { this.size = size; } @@ -2063,7 +2086,7 @@ class Labrador extends Dog { super(name); this.size = size; } - // 4 + // 4 constructor(name, size) { this.name = name; this.size = size; @@ -2124,7 +2147,7 @@ Das ist der große Unterschied zwischen `require()` in CommonJS und `import`. Mi --- -###### 68. Was ist der Output? +###### 68. Was wird ausgegeben? ```javascript console.log(Number(2) === Number(2)) @@ -2142,14 +2165,14 @@ console.log(Symbol('foo') === Symbol('foo')) #### Antwort: A -Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt. +Jedes Symbol ist eindeutig. Der Sinn des Argumentes, welches an das Symbol weitergegeben wird, ist dem Symbol eine Beschreibung zu geben. Der Wert des Symbols hängt nicht von diesem Argument ab. Beim vergleichen der Symbole werden zwei komplett neue Symbole erstellt: das erste `Symbol('foo')` und das zweite `Symbol('foo')`. Diese beiden Werte sind eindeutig und nicht identisch, weshalb `Symbol('foo') === Symbol('foo')` `false` ausgibt.

--- -###### 69. Was ist der Output? +###### 69. Was wird ausgegeben? ```javascript const name = "Lydia Hallie" @@ -2160,7 +2183,7 @@ console.log(name.padStart(2)) - A: `"Lydia Hallie"`, `"Lydia Hallie"` - B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) - C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, +- D: `"Lydia Hallie"`, `"Lyd"`,
Antwort

@@ -2176,7 +2199,7 @@ Falls der Wert, der an `padStart` übergeben wurde kleiner ist, als die Länge d --- -###### 70. Was ist der Output? +###### 70. Was wird ausgegeben? ```javascript console.log("🥑" + "💻"); @@ -2236,7 +2259,7 @@ Wenn wir `game.next("Yes").value` aufrufen wird das vorhergehende `yield` durch --- -###### 72. Was ist der Output? +###### 72. Was wird ausgegeben? ```javascript console.log(String.raw`Hello\nworld`); @@ -2271,7 +2294,7 @@ In unserem Fall ist das Ergebnis `Hello\nworld`, was geloggt wird. --- -###### 73. Was ist der Output? +###### 73. Was wird ausgegeben? ```javascript async function getData() { @@ -2305,7 +2328,7 @@ Das hätte `"I made it!"` ausgegeben. --- -###### 74. Was ist der Output? +###### 74. Was wird ausgegeben? ```javascript function addToList(item, list) { @@ -2335,7 +2358,7 @@ Die `push` Methode verändert das ursprüngliche Array. Wenn wir das _Array_ der --- -###### 75. Was ist der Output? +###### 75. Was wird ausgegeben? ```javascript const box = { x: 10, y: 20 }; @@ -2370,7 +2393,7 @@ Da `shape` eingefroren ist und der Wert von `x` kein Objekt ist, können wir den --- -###### 76. Was ist der Output? +###### 76. Was wird ausgegeben? ```javascript const { name: myName } = { name: "Lydia" }; @@ -2424,7 +2447,7 @@ Die `sum` Funktion gibt daher immer das gleiche Ergebnis aus. Wenn wir `1` und ` --- -###### 78. Was ist der Output? +###### 78. Was wird ausgegeben? ```javascript const add = () => { @@ -2471,7 +2494,7 @@ Beim dritten Mal geben wir `5 * 2` als Argument in die Funktion ein, was `10` er --- -###### 79. Was ist der Output? +###### 79. Was wird ausgegeben? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2508,7 +2531,7 @@ Mit einer _for-of_ Schleife können wir über **wiederholbare** Elemente iterier --- -###### 80. Was ist der Output? +###### 80. Was wird ausgegeben? ```javascript const list = [1 + 2, 1 * 2, 1 / 2] @@ -2534,7 +2557,7 @@ Das Element ist gleich dem ausgegebenen Wert. `1 + 2` ergibt `3`, `1 * 2` ergibt --- -###### 81. Was ist der Output? +###### 81. Was wird ausgegeben? ```javascript function sayHi(name) { @@ -2567,7 +2590,7 @@ In diesem Fall, falls wir kein Argument oder `undefined` eingeben ist `name` imm --- -###### 82. Was ist der Output? +###### 82. Was wird ausgegeben? ```javascript var status = "😎" @@ -2607,7 +2630,7 @@ Mit der `call` Methode können wir das Objekt, auf welches sich das `this` Keywo --- -###### 83. Was ist der Output? +###### 83. Was wird ausgegeben? ```javascript const person = { @@ -2644,7 +2667,7 @@ Wenn wir `person` loggen bekommen wir daher das unveränderte Objekt angezeigt. --- -###### 84. Was ist der Output? +###### 84. Was wird ausgegeben? ```javascript function checkAge(age) { @@ -2688,7 +2711,7 @@ fetch('https://www.website.com/api/user/1') - A: Das Ergebnis der `fetch` Methode. - B: Das Ergebnis des zweiten Aufrufs der `fetch` Methode. - C: Das Ergebnis des Callbacks im vorhergehenden `.then()`. -- D: Immer `undefined`. +- D: Immer `undefined`.

Antwort

@@ -2733,7 +2756,7 @@ Wenn wir `hasName` gleich `name` setzen, so beinhaltet `hasName` den Wert von `n --- -###### 87. Was ist der Output? +###### 87. Was wird ausgegeben? ```javascript console.log("I want pizza"[0]) @@ -2758,7 +2781,7 @@ Diese Methode funktioniert nicht in IE7 und davor. Hier muss `.charAt()` verwend --- -###### 88. Was ist der Output? +###### 88. Was wird ausgegeben? ```javascript function sum(num1, num2 = num1) { @@ -2787,14 +2810,14 @@ Wenn man den Wert des Standard Paramenters gleich dem Parameter setztm der _dana --- -###### 89. Was ist der Output? +###### 89. Was wird ausgegeben? ```javascript -// module.js +// module.js export default () => "Hello world" export const name = "Lydia" -// index.js +// index.js import * as data from "./module" console.log(data) @@ -2819,7 +2842,7 @@ Das `data` Objekt hat eine Standard Property für alle Standard Exporte, andere --- -###### 90. Was ist der Output? +###### 90. Was wird ausgegeben? ```javascript class Person { @@ -2857,7 +2880,7 @@ Das Aufrufen eines Funktionskonstruktors mit `new` hat zur Folge, dass eine Inst --- -###### 91. Was ist der Output? +###### 91. Was wird ausgegeben? ```javascript let newList = [1, 2, 3].push(4) @@ -2884,7 +2907,7 @@ Dann versuchen wir die `.push` Methode auf `newList` anzuwenden. Da `newList` de --- -###### 92. Was ist der Output? +###### 92. Was wird ausgegeben? ```javascript function giveLydiaPizza() { @@ -2897,8 +2920,8 @@ console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) ``` -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` - C: `{ constructor: ...}` `{}` - D: `{ constructor: ...}` `undefined` @@ -2907,14 +2930,14 @@ console.log(giveLydiaChocolate.prototype) #### Antwort: D -Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen. +Reguläre Funktionen wie `giveLydiaPizza` haben eine `prototype` Property, die ein Objekt (Prototype Object) mit einem `constructor` ist. Arrow Funktionen dagegen (wie `giveLydiaChocolate`) haben keinen `prototype`. `undefined` wird ausgegeben, wenn wir versuchen den `prototype` mit `giveLydiaChocolate.prototype` aufzurufen.

--- -###### 93. Was ist der Output? +###### 93. Was wird ausgegeben? ```javascript const person = { @@ -2928,7 +2951,7 @@ for (const [x, y] of Object.entries(person)) { ``` - A: `name` `Lydia` und `age` `21` -- B: `["name", "Lydia"]` und `["age", 21]` +- B: `["name", "Lydia"]` und `["age", 21]` - C: `["name", "age"]` und `undefined` - D: `Error` @@ -2939,7 +2962,7 @@ for (const [x, y] of Object.entries(person)) { `Object.entries(person)` gibt ein Array mit verschachtelten Arrays der Keys aus: -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` Mit der `for-of` Schleife iterieren wir über jedes Element in dem Array, in diesem Fall die verschachtelten Arrays. Wir können die verschachtelten Arrays mit `const [x, y]` in der for-of Schleife destrukturieren. `x` ist gleich dem ersten Element, `y` ist gleich dem zweiten Element in dem verschachtelten Array. @@ -2951,7 +2974,7 @@ Das zweite verschachtelte Array ist `[ "age", 21 ]`. `x` ist gleich `"age"` und --- -###### 94. Was ist der Output? +###### 94. Was wird ausgegeben? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -2962,7 +2985,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` - A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` - C: `["banana", "apple", ["pear"], "orange"]` - D: `SyntaxError` @@ -2987,16 +3010,16 @@ Dieses Beispiel würde funktionieren und `[ 'banana', 'apple', 'orange', 'pear' --- -###### 95. Was ist der Output? +###### 95. Was wird ausgegeben? ```javascript function nums(a, b) { if (a > b) console.log('a is bigger') - else + else console.log('b is bigger') - return + return a + b } @@ -3031,7 +3054,7 @@ Bedenke: Semikolons werden **nicht** automatisch nach `if/else` Statements geset --- -###### 96. Was ist der Output? +###### 96. Was wird ausgegeben? ```javascript class Person { @@ -3067,7 +3090,7 @@ Wir können Klassen gleich anderen Klassen oder Funktions Konstruktoren setzen. --- -###### 97. Was ist der Output? +###### 97. Was wird ausgegeben? ```javascript const info = { @@ -3098,7 +3121,7 @@ Bedenke: Man kann die Symbole dennoch mit der `Object.getOwnPropertySymbols()` M --- -###### 98. Was ist der Output? +###### 98. Was wird ausgegeben? ```javascript const getList = ([x, ...y]) => [x, y] @@ -3138,7 +3161,7 @@ Da kein Wert ausgegeben wird, gibt die Funktion `undefined` aus. --- -###### 99. Was ist der Output? +###### 99. Was wird ausgegeben? ```javascript const name = "Lydia" @@ -3169,7 +3192,7 @@ ReferenceErrors werden ausgeworfen, wenn JavaScript eine Referenz zu einem Wert --- -###### 100. Was ist der Output? +###### 100. Was wird ausgegeben? ```javascript // 🎉✨ Das ist unsere 100. Frage! ✨🎉 @@ -3197,7 +3220,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` --- -###### 101. Was ist der Output? +###### 101. Was wird ausgegeben? ```javascript const one = (false || {} || null) @@ -3260,19 +3283,19 @@ Mit einem Promise sagen wir _Ich möchte diese Funktion ausführen, aber ich leg Wir können auf den Wert mit `.then()` oder `await` in einer `async` Funktion zugreifen, aber `.then()` und `await` unterscheiden sich in einem bestimmten Punkt. -In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. -Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. +In `firstFunction` legen wir `myPromise` beiseite, während die Funktion durchläuft, aber wir arbeiten anderen Code ab, hier `console.log('second')`. +Dann wird die Funktion abgeschlossen und der String `I have resolved` wird ausgegeben, nachdem sich der Call Stack geleert hat. Mit dem `await` Keyword in `secondFunction` wird die Funktion gestoppt bis der Wert ausgegeben wurde, erst dann wird die nächste Zeile ausgeführt. -Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt. +Das bedeutet, dass auf `myPromise` gewartet und dann der Wert `I have resolved` ausgegeben wird und erst dann wird die nächste Zeile ausgeführt und `second` wird geloggt.

--- -###### 103. Was ist der Output? +###### 103. Was wird ausgegeben? ```javascript const set = new Set() @@ -3300,7 +3323,7 @@ Der `+` Operator wird nicht nur für numerische Werte verwendet, wir können mit Der erste Wert ist `1`, was ein numerischer Wert ist. `1 + 2` ergibt die Zahl `3`. -Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. +Der zweite Wert hingegen ist der String `"Lydia"`. `"Lydia"` ist ein String und `2` ist eine Nummer: `2` wird in einem String umgewandelt. `"Lydia"` und `"2"` werden zusammengesetzt, was den String `"Lydia2"` ausgibt. `{ name: "Lydia" }` ist ein Objekt. Weder eine Nummer, noch ein Objekt sind ein String, aber beide werden zu Strings konvertiert und `"[object Object]"` wird ausgegeben. `"[object Object]"` zusammengesetzt mit `"2"` wird `"[object Object]2"`. @@ -3317,7 +3340,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Antwort @@ -3325,9 +3348,9 @@ Promise.resolve(5) #### Antwort: C -Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt. Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. +Wir können jeden Wert an `Promise.resolve` übergeben, es muss nicht unbedingt ein Promise sein. Die Methode selbst gibt ein Promise zurück, was einen Wert ausgibt (``). Wenn man eine normale Funktion übergibt wird das Promise einen normalen Wert ausgeben. Wenn ein Promise übergeben wird so wird ein Promise gelöst und der Wert des gelösten Promises ausgegeben. -In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`. +In diesem Fall haben wir nur die Zahl `5` übergeben und diese wird genauso ausgegeben: `5`.

@@ -3366,7 +3389,7 @@ Wir setzen den Standardwert für `person2` gleich dem `person` Objekt und überg Das bedeutet, dass beide Werte eine Referenz zum gleichen Ort im Speicher aufweisen und daher gleich sind. -Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt. +Der Code im `else` Statement wird aufgerufen und `They are the same!` wird geloggt.

@@ -3399,7 +3422,7 @@ console.log(colorConfig.colors[1]) #### Antwort: D -In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). +In JavaScript gibt es zwei Wege auf Properties an Objekten zuzugreifen: Punkt-Notation oder Klammern-Notation. In diesem Beispiel nutzen wir Punkt-Notation (`colorConfig.colors`) anstelle von Klammern-Notation (`colorConfig["colors"]`). Mit Punkt-Notation versucht JavaScript die Property am Objekt mit diesem exakten Namen zu finden. In unserem Beispiel `colors` im `colorConfig` Objekt. Da es keine Property `colorConfig` gibt wird `undefined` ausgegeben. Dann versuchen wir den Wert des ersten Elements mit `[1]` aufzurufen, was an `undefined` nicht möglich ist, wodurch wir `TypeError: Cannot read property '1' of undefined` ausgegeben bekommen. @@ -3431,7 +3454,7 @@ Emojis sind im Endeffekt nur Unicodes. Der Unicode für das Herz Emoji ist `"U+2 --- -###### 108. Welche Methode verändert das ursprüngliche Array? +###### 108. Welche Methode verändert das ursprüngliche Array? ```javascript const emojis = ['✨', '🥑', '😍'] @@ -3440,13 +3463,13 @@ emojis.map(x => x + '✨') emojis.filter(x => x !== '🥑') emojis.find(x => x !== '🥑') emojis.reduce((acc, cur) => acc + '✨') -emojis.slice(1, 2, '✨') +emojis.slice(1, 2, '✨') emojis.splice(1, 2, '✨') ``` - A: `All of them` - B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` +- C: `map` `slice` `splice` - D: `splice`
Antwort @@ -3454,7 +3477,7 @@ emojis.splice(1, 2, '✨') #### Antwort: D -Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. +Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, ersetzen oder ergänzen von Elementen. In diesem Fall haben wir 2 Elemente vom Index 1 (`'🥑'` und `'😍'`) entfernt und ✨ stattdessen eingefügt. `map`, `filter` und `slice` geben ein neues Array aus, `find` gibt ein Element aus und `reduce` gibt einen neuen Wert aus. @@ -3464,7 +3487,7 @@ Mit der `splice` Methode ändern wir das ursprüngliche Array durch löschen, er --- -###### 109. Was ist der Output? +###### 109. Was wird ausgegeben? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3477,7 +3500,7 @@ console.log(food) - A: `['🍕', '🍫', '🥑', '🍔']` - B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` - D: `ReferenceError`
Antwort @@ -3531,7 +3554,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. Was ist der Output? +###### 111. Was wird ausgegeben? ```javascript let name = 'Lydia' @@ -3575,7 +3598,7 @@ getName() // Lydia --- -###### 112. Was ist der Output? +###### 112. Was wird ausgegeben? ```javascript function* generatorOne() { @@ -3626,7 +3649,7 @@ console.log(two.next().value) // undefined --- -###### 113. Was ist der Output? +###### 113. Was wird ausgegeben? ```javascript console.log(`${(x => x)('I love')} to program`) @@ -3642,7 +3665,7 @@ console.log(`${(x => x)('I love')} to program`) #### Antwort: A -Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`. +Expressions innerhalb von Template Literals werden zuerst berechnet. Das bedeutet, dass der String den ausgegebenen Wert der Expression beinhaltet, hier die IIFE (immediately invoked Function) `(x => x)('I love')`. Wir geben den Wert `'I love'` als Argument an die `x => x` Arrow Funktion. `x` ist gleich `'I love'` und wird ausgegeben. Das Ergebnis ist `I love to program`.

@@ -3704,7 +3727,7 @@ myMap.get(() => 'greeting')) #### Antwort: B -Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. +Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes Argument an die `set` Funktion übergeben und der Wert wird als zweites Argument eingegeben. Der Key ist die _Funktion_ `() => 'greeting'` und der Wert ist `'Hello world'`. `myMap` ist jetzt `{ () => 'greeting' => 'Hello world!' }`. 1 ist falsch, weil der Key nicht `'greeting'`, sondern `() => 'greeting'` ist. 3 ist falsch, weil wir eine neue Funktion erstellen, indem wir sie als Argument übergeben. Objekte interagieren anhand von _Referenzen_. Funktionen sind Objekte, weshalb zwei Funktionen streng gesehen nie gleich sind, selbst wenn sie sich nicht unterscheiden. @@ -3714,7 +3737,7 @@ Beim Setzen eines Key/Wert Paars mit der `set` Methode wird der Key als erstes A --- -###### 116. Was ist der Output? +###### 116. Was wird ausgegeben? ```javascript const person = { @@ -3752,3 +3775,551 @@ Dann führen wir `changeAgeAndName` aus, allerdings ohne Parameter. Stattdessen

+ +--- + +###### 117. Welche der beiden Optionen wird `6` ausgeben? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Antwort +

+ +#### Antwort: C + +Mit dem Spread-Operator `...` können wir Werte _spreaden_ ("verstreichen"). Die `sumValues` Funktion erhält drei Argumente: `x`, `y` und `z`. `...[1, 2, 3]` ergibt `1, 2, 3`, was wir an `sumValues` übergeben. + +

+
+ +--- + +###### 118. Was ist der Output?? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: B + +Mit dem`+=` Operanden erhöhen wir den Wert von `num` um `1`. `num` hatte den ursprünglichen Wert `1` und `1 + 1` ergibt `2`. Der Wert an zweiter Stelle im `list` Array ist 🥰. `console.log(list[2])` gibt 🥰 aus. + +

+
+ +--- + +###### 119. Was ist der Output?? + +```javascript +const person = { + firstName: "Lydia", + lastName: "Hallie", + pet: { + name: "Mara", + breed: "Dutch Tulip Hound" + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Antwort +

+ +#### Antwort: B + +Mit den optionalen Kettenoperator `?.` müssen wir nicht mehr prüfen, ob die tiefer genesteten Werte gültig sind oder nicht. Wenn wir die Property von `undefined` oder `null` aufrufen (_nullish_) gibt die Expression direkt `undefined` aus. + +`person.pet?.name`: `person` hat eine Property `pet`: `person.pet` ist nicht nullish. Diese hat eine Property `name` und gibt `Mara` aus. +`person.pet?.family?.name`: `person` hat eine Property `pet`: `person.pet` ist nicht nullish. `pet` hat _keine_ Property `family`, `person.pet.family` ist nullish. Die Expression gibt `undefined` aus. +`person.getFullName?.()`: `person` hat eine Property `getFullName`: `person.getFullName()` ist nicht nullish und wird ausgeführt: `Lydia Hallie` wird ausgegeben. +`member.getLastName?.()`: `member` ist undefined: `member.getLastName()` ist nullish. Die Expression gibt `undefined` aus. + +

+
+ +--- + +###### 120. Was ist der Output?? + +```javascript +const groceries = ["banana", "apple", "peanuts"]; + +if (groceries.indexOf("banana")) { + console.log("We have to buy bananas!"); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Antwort +

+ +#### Antwort: B + +Wir haben die Kondition `groceries.indexOf("banana")` an das if-Statement übergeben. `groceries.indexOf("banana")` gibt `0` aus, was ein _falsy_ Wert ist. Da die Kondition nicht erfüllt ist wird der `else` Block ausgeführt und `We don't have to buy bananas!` wird geloggt. + +

+
+ +--- + +###### 121. Was ist der Output? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + } +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang) }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Antwort +

+ +#### Antwort: D + +Die Methode `language` ist ein `setter`. Setter halten keinen Wert, sondern ändern Properties. Wenn eine `setter` Methode aufgerufen wird, wird `undefined` zurückgegeben. + +

+
+ +--- + +###### 122. Was ist der Output?? + +```javascript +const name = "Lydia Hallie"; + +console.log(!typeof name === "object"); +console.log(!typeof name === "string"); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Antwort +

+ +#### Antwort: C + +`typeof name` gibt `"string"` aus. Der String `"string"` ist _truthy_, sodass `!typeof name` den Boolean-Wert `false` ergibt. `false === "object"` und `false === "string"` geben beide `false` aus. + +(Würden wir prüfen wollen, oob der Typ (un)gleich zu einem bestimmten anderen Typen ist hätten wir `!==` anstelle von `!typeof` schreiben müssen) + +

+
+ +--- + +###### 123. Was ist der Output?? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Antwort +

+ +#### Antwort: A + +Die `add` Funktion gibt eine Arrow Funktion zurück, welche eine Arrow Funktion zurückgibt, welche eine Arrow Funktion zurückgibt. Die erste Funktion erhält ein Argument `x` mit dem Wert `4`. Wir führen die zweite Funktion aus, welche ein Argument `y` mit dem Wert `5` erhält. Dann führen wir die dritte Funktion aus, die ein Argument `z` mit dem Wert `6` erhält. Wenn wir versuchen die Werte von `x`, `y` und `z` der jeweils letzten Arrow Funktion aufzurufen geht die JavaScript Engine in der Scope-Kette nach oben um die jeweiligen Werte zu finden. Das gibt `4` `5` `6` aus. + +

+
+ +--- + +###### 124. Was ist der Output?? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Antwort +

+ +#### Antwort: C + +Die Generator-Funktion `range` gibt ein asynchrones Objekt mit Promisen für jeden Wert zurück: `Promise{1}`, `Promise{2}`, `Promise{3}`. Wir setzen die Variable `gen` gleich dem asynchronen Objekt. Danach loopen wir mit einer `for await ... of` Schleife darüber. Wir setzen die Variable `item` gleich dem ausgegebenen Promise: zuerst `Promise{1}`, dann `Promise{2}`, und dann `Promise{3}`. Da wir das Ergebnis von `item` _await_-en (erwarten), werden die gelösten Ergebnisse der Promises ausgegeben: `1`, `2` und `3`. + +

+
+ +--- + +###### 125. Was ist der Output?? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Antwort +

+ +#### Antwort: D + +`myFunc` erwartet ein Objekt mit den Properties `x`, `y` und `z` als Argumente. Da wir nur drei separate Werte anstelle eines Objektes mit den Properties `x`, `y` und `z` ({x: 1, y: 2, z: 3}) eingeben, bekommen `x`, `y` und `z` den Standardwert `undefined` zugewiesen. + +

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

+ +#### Antwort: B + +Mit der Methode `Intl.NumberFormat` können wir einen numerischen Wert in einen sprachabhängigen Wert formatieren. Wir formatieren den Zahlenwert `130` zu einem Wert der Sprache `en-US` mit der Einheit (`unit`) in `mile-per-hour`, was `130 mph` ergibt. Analog formatieren wir `300` als eine Währung (`currency`) der Sprache `en-US` in `USD`, was `$300.00` ergibt. + +

+
+ +--- + +###### 127. Was ist der Output? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Antwort +

+ +#### Antwort: B + +Durch die destrukturierende Zuweisung können wir Werte des Ojekts von der rechten Seite der Zuweisung extrahieren und diese Werte einem Property mit dem selben Namen dem Objekt auf der linken Seite zuweisen. In diesem Fall wird der Wert "💀" an `spookyItems[3]` zugewiesen. Das bedeutet, dass wir das Array `spookyItems` modifizieren, in dem wir "💀" hinzufügen. Beim Loggen von `spookyItems` wird darum `["👻", "🎃", "🕸", "💀"]` ausgegeben. + +

+
+ +--- + +###### 128. Was ist der Output? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Antwort +

+ +#### Antwort: C + +Mit der Methode `Number.isNaN` kann geprüft werden, ob der übergebene Parameter vom Typ _Number_ mit Wert `NaN` ist. `name` ist kein numerischer Wert, deswegen ist der Rückgabewert von `Number.isNaN(name)` in diesem Fall `false`. `age` ist zwar ein numerischer Wert, aber nicht gleich `NaN`, weswegen `Number.isNaN(age)` `false` ausgibt. + +Die Methode `isNaN` prüft, ob der Eingabeparameter nicht vom Typ _Number_ ist. `name` ist ein String, darum gibt `isNaN(name)` `true` zurück. `age` ist ein numerischer Wert, weswegen `isNaN(age)` `false` ausgibt. + +

+
+ +--- + +###### 129. Was ist der Output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Antwort +

+ +#### Antwort: D + +Variablen die mit `const` deklariert werden, können nicht vor ihrer Initialisierung referenziert werden, das ist die so genannte "zeitweilige tote Zone" (_temporal dead zone_). In der Funktion `getInfo` befindet sich die Variable `randomValue` im Geltungsbereich der Funktion. In der Zeile, in welcher der Wert von `typeof randomValue` geloggt werden soll, ist die Variable noch nicht initialisiert. Entsprechend wird ein `ReferenceError` geworfen! Die Engine versucht nicht in der Kette der Geltungsbereiche hinab zu steigen, da die Variable `randomValue` im Geltungsbereich von `getInfo` deklariert und damit gefunden wurde. + +

+
+ +--- + +###### 130. Was ist der Output? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Antwort +

+ +#### Antwort: C + +Im `try`-Block loggen wir den mit dem `await`-Operator den Wert der Variable `myPromise`: `"Woah some cool data"`. Da in diesem Block kein Fehler geworfen wird, wird der Code im `catch`-Block nicht ausgeführt. Der Code im `finally`-Block wird _immer_ ausgeführt, `"Oh finally!"` wird geloggt. + +

+
+ +--- + +###### 131. Was ist der Output? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Antwort +

+ +#### Antwort: B + +Mit der Methode `flat` erzeugen wir ein neues, "flacheres" Array. Die Tiefe des neuen Arrays hängt vom Parameter ab, den wir an `flat` übergeben. In diesem Fall wird der Wert `1` übergeben (welcher der Standardwert der Funktion ist, wir hätten ihn in diesem Fall also nicht explizit übergeben müssen). Das bedeutet, das alle Arrays bis zur ersten Tiefe zusammengefügt werden: `['🥑']` und `['✨', '✨', ['🍕', '🍕']]` in diesem Fall. Das Zusammenfügen dieser beiden Arrays resultiert in: `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Was ist der Output? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Antwort +

+ +#### Antwort: D + +`counterOne` ist eine Instanz der Klasse `Counter`. Diese Klasse enthält ein Property `count` in seinem Konstruktor, sowie eine Methode `increment`. Zuerst wird die Methode `increment` zweimal durch `counterOne.increment()` aufgerufen. Der Wert von `counterOne.count` ist danach `2`. + + + +Danach erzeugen wir eine neue Variable `counterTwo` und setzen sie gleich `counterOne`. Da Objekte via Referenz übergeben werden, erzeugen wir somit lediglich eine neue Referenz auf den selben Bereich im Speicher, auf den auch `counterOne` zeigt. Da der gleiche Speicherbereich verwendet wird, haben alle Änderungen, die am Objekt vorgenommen werden, auf das `counterTwo` zeigt, auch Auswirkungen auf `counterOne`. Aktuell ist `counterTwo.count` somit `2`. + +Wir rufen nun `counterTwo.increment()` auf, wodurch der Wert von `count` auf `3` gesetzt wird. Danach loggen wir den Zustand von `counterOne`, wodurch `3` ausgegeben wird. + + + +

+
+ +--- + +###### 133. Was ist der Output? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise!')); + +function funcOne() { + myPromise.then(res => res).then(res => console.log(res)); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(await res); + setTimeout(() => console.log('Timeout!', 0)); + console.log('Last line!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise! Last line! Promise! Last line! Last line! Promise!` +- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` +- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` +- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +
Antwort +

+ +#### Antwort: D + +Zuerst rufen wir die Funktion `funcOne()` auf. In der ersten Zeile in `funcOne` wird das Promise `myPromise` aufgerufen, was eine _asynchrone_ Operation ist. Während die Engine damit beschäftigt ist dieses Promise zu erfüllen, wird die Funktion `funcOne` weiter ausgeführt. Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, von welcher der Callback an die Web API geschickt wird (siehe mein Artikel zu Event Loops). + +Sowohl Promise als auch Timeout sind asynchrone Operationen. Die Funktion läuft also weiter, während sie parallel damit beschäfigt ist diese beiden Operationen zu bearbeiten. Das bedeutet, dass `Last line!` zuerst geloggt wird, da dies keine asynchrone Operation ist. Es ist die letzte Zeile von `funcOne`, das Promise wird erfüllt und `Promise!` geloggt. Da wir jedoch auch `funcTwo()` aufrufen, ist der Call Stack nicht leer und der Callback der Funktion `setTimeout` kann noch nicht zum Call Stack hinzugefügt werden. + +In `funcTwo` warten wir zuerst auf das Promise von `myPromise`. Mit dem `await`-Operator pausieren wir die Ausführung der Funktion bis das Promise erfüllt (oder zurück gewiesen) wurde. Anschließend loggen wir (wieder mit dem `await-Operator`, da das Promise selbst ein Promise zurückgibt) den Wert von `res`. Dadurch wird `Promise!` geloggt. + +Die nächste Zeile ist die _asynchrone_ Funktion `setTimeout`, deren Callback an die Web API gesendet wird. + +Wir kommen zur letzten Zeile in `funcTwo`, die `Last line!` in der Console ausgibt. Da `funcTwo` abgearbeitet und aus dem Call Stack entfernt wurde, ist der Call Stack leer. Die wartenden Callbacks (`() => console.log("Timeout!")` aus `funcOne` und `() => console.log("Timeout!")` aus `funcTwo`) werden dem Call Stack nacheinander hinzugefügt. Der erste Callback loggt `Timeout!` und wird aus dem Stack entfernt. Anschließend loggt der zweite Callback `Timeout!` und wird aus dem Stack entfernt. Somit ist das Ergebnis `Last line! Promise! Promise! Last line! Timeout! Timeout!` + +

+
\ No newline at end of file diff --git a/en-EN/README.md b/en-EN/README.md deleted file mode 100644 index f309e06f..00000000 --- a/en-EN/README.md +++ /dev/null @@ -1,4992 +0,0 @@ -
- -

JavaScript Questions

- ---- - - -I post multiple choice JavaScript questions on my [Instagram](https://www.instagram.com/theavocoder) **stories**, which I'll also post here! Last updated: June 8th - -From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart: - -Feel free to reach out to me! 😊
- Instagram || Twitter || LinkedIn || Blog -
- ---- - -
See 16 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 -

- -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) -* [Indonesia](../id-ID/README.md) - -

-
- ---- - -###### 1. What's the output? - -```javascript -function sayHi() { - console.log(name); - console.log(age); - var name = 'Lydia'; - let age = 21; -} - -sayHi(); -``` - -- A: `Lydia` and `undefined` -- B: `Lydia` and `ReferenceError` -- C: `ReferenceError` and `21` -- D: `undefined` and `ReferenceError` - -
Answer -

- -#### Answer: D - -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. - -Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. - -

-
- ---- - -###### 2. What's the output? - -```javascript -for (var i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); -} - -for (let i = 0; i < 3; i++) { - setTimeout(() => console.log(i), 1); -} -``` - -- A: `0 1 2` and `0 1 2` -- B: `0 1 2` and `3 3 3` -- C: `3 3 3` and `0 1 2` - -
Answer -

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

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

- -#### Answer: B - -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. - -With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example). - -There is no value `radius` on that object, which returns `undefined`. - -

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

- -#### Answer: A - -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. - -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. - -

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

- -#### Answer: A - -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. - -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. - -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` - -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. - -

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

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

-
- ---- - -###### 7. What's the output? - -```javascript -let a = 3; -let b = new Number(3); -let c = 3; - -console.log(a == b); -console.log(a === b); -console.log(b === c); -``` - -- A: `true` `false` `true` -- B: `false` `false` `true` -- C: `true` `false` `false` -- D: `false` `true` `true` - -
Answer -

- -#### Answer: C - -`new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. - -When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. - -However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.` - -

-
- ---- - -###### 8. What's the output? - -```javascript -class Chameleon { - static colorChange(newColor) { - this.newColor = newColor; - return this.newColor; - } - - constructor({ newColor = 'green' } = {}) { - this.newColor = newColor; - } -} - -const freddie = new Chameleon({ newColor: 'purple' }); -console.log(freddie.colorChange('orange')); -``` - -- A: `orange` -- B: `purple` -- C: `green` -- D: `TypeError` - -
Answer -

- -#### Answer: D - -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since `freddie` is a child, the function is not passed down, and not available on the `freddie` instance: a `TypeError` is thrown. - -

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

- -#### Answer: A - -It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as `global.greetign = {}` (or `window.greetign = {}` in a browser). - -In order to avoid this, we can use `"use strict"`. This makes sure that you have declared a variable before setting it equal to anything. - -

-
- ---- - -###### 10. What happens when we do this? - -```javascript -function bark() { - console.log('Woof!'); -} - -bark.animal = 'dog'; -``` - -- A: Nothing, this is totally fine! -- B: `SyntaxError`. You cannot add properties to a function this way. -- C: `"Woof"` gets logged. -- D: `ReferenceError` - -
Answer -

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

-
- ---- - -###### 11. What's the output? - -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; -} - -const member = new Person('Lydia', 'Hallie'); -Person.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; - -console.log(member.getFullName()); -``` - -- A: `TypeError` -- B: `SyntaxError` -- C: `Lydia Hallie` -- D: `undefined` `undefined` - -
Answer -

- -#### Answer: A - -You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case, - -```js -Person.prototype.getFullName = function() { - return `${this.firstName} ${this.lastName}`; -}; -``` - -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! - -

-
- ---- - -###### 12. What's the output? - -```javascript -function Person(firstName, lastName) { - this.firstName = firstName; - this.lastName = lastName; -} - -const lydia = new Person('Lydia', 'Hallie'); -const sarah = Person('Sarah', 'Smith'); - -console.log(lydia); -console.log(sarah); -``` - -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` - -
Answer -

- -#### Answer: A - -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! - -We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. - -

-
- ---- - -###### 13. What are the three phases of event propagation? - -- A: Target > Capturing > Bubbling -- B: Bubbling > Target > Capturing -- C: Target > Bubbling > Capturing -- D: Capturing > Target > Bubbling - -
Answer -

- -#### Answer: D - -During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins. - - - -

-
- ---- - -###### 14. All object have prototypes. - -- A: true -- B: false - -
Answer -

- -#### Answer: B - -All objects have prototypes, except for the **base object**. The base object is the object created by the user, or an object that is created using the `new` keyword. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you. - -

-
- ---- - -###### 15. What's the output? - -```javascript -function sum(a, b) { - return a + b; -} - -sum(1, '2'); -``` - -- A: `NaN` -- B: `TypeError` -- C: `"12"` -- D: `3` - -
Answer -

- -#### Answer: C - -JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another. - -In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`. - -

-
- ---- - -###### 16. What's the output? - -```javascript -let number = 0; -console.log(number++); -console.log(++number); -console.log(number); -``` - -- A: `1` `1` `2` -- B: `1` `2` `2` -- C: `0` `2` `2` -- D: `0` `1` `2` - -
Answer -

- -#### Answer: C - -The **postfix** unary operator `++`: - -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) - -The **prefix** unary operator `++`: - -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) - -This returns `0 2 2`. - -

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

- -#### Answer: B - -If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions! - -

-
- ---- - -###### 18. What's the output? - -```javascript -function checkAge(data) { - if (data === { age: 18 }) { - console.log('You are an adult!'); - } else if (data == { age: 18 }) { - console.log('You are still an adult.'); - } else { - console.log(`Hmm.. You don't have an age I guess`); - } -} - -checkAge({ age: 18 }); -``` - -- A: `You are an adult!` -- B: `You are still an adult.` -- C: `Hmm.. You don't have an age I guess` - -
Answer -

- -#### Answer: C - -When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory. - -The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality. - -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. - -

-
- ---- - -###### 19. What's the output? - -```javascript -function getAge(...args) { - console.log(typeof args); -} - -getAge(21); -``` - -- A: `"number"` -- B: `"array"` -- C: `"object"` -- D: `"NaN"` - -
Answer -

- -#### Answer: C - -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` - -

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

- -#### Answer: C - -With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object. - -

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

- -#### Answer: A - -`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. - -

-
- ---- - -###### 22. How long is cool_secret accessible? - -```javascript -sessionStorage.setItem('cool_secret', 123); -``` - -- A: Forever, the data doesn't get lost. -- B: When the user closes the tab. -- C: When the user closes the entire browser, not only the tab. -- D: When the user shuts off their computer. - -
Answer -

- -#### Answer: B - -The data stored in `sessionStorage` is removed after closing the _tab_. - -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. - -

-
- ---- - -###### 23. What's the output? - -```javascript -var num = 8; -var num = 10; - -console.log(num); -``` - -- A: `8` -- B: `10` -- C: `SyntaxError` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. - -You cannot do this with `let` or `const` since they're block-scoped. - -

-
- ---- - -###### 24. What's the output? - -```javascript -const obj = { 1: 'a', 2: 'b', 3: 'c' }; -const set = new Set([1, 2, 3, 4, 5]); - -obj.hasOwnProperty('1'); -obj.hasOwnProperty(1); -set.has('1'); -set.has(1); -``` - -- A: `false` `true` `false` `true` -- B: `false` `true` `true` `true` -- C: `true` `true` `false` `true` -- D: `true` `true` `true` `true` - -
Answer -

- -#### Answer: C - -All object keys (excluding Symbols) are strings under the hood, even if you don't type it yourself as a string. This is why `obj.hasOwnProperty('1')` also returns true. - -It doesn't work that way for a set. There is no `'1'` in our set: `set.has('1')` returns `false`. It has the numeric type `1`, `set.has(1)` returns `true`. - -

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

- -#### Answer: C - -If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value. - -

-
- ---- - -###### 26. The JavaScript global execution context creates two things for you: the global object, and the "this" keyword. - -- A: true -- B: false -- C: it depends - -
Answer -

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

-
- ---- - -###### 27. What's the output? - -```javascript -for (let i = 1; i < 5; i++) { - if (i === 3) continue; - console.log(i); -} -``` - -- A: `1` `2` -- B: `1` `2` `3` -- C: `1` `2` `4` -- D: `1` `3` `4` - -
Answer -

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

-
- ---- - -###### 28. What's the output? - -```javascript -String.prototype.giveLydiaPizza = () => { - return 'Just give Lydia pizza already!'; -}; - -const name = 'Lydia'; - -name.giveLydiaPizza(); -``` - -- A: `"Just give Lydia pizza already!"` -- B: `TypeError: not a function` -- C: `SyntaxError` -- D: `undefined` - -
Answer -

- -#### Answer: A - -`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! - -

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

- -#### Answer: B - -Object keys are automatically converted into strings. We are trying to set an object as a key to object `a`, with the value of `123`. - -However, when we stringify an object, it becomes `"[object Object]"`. So what we are saying here, is that `a["object Object"] = 123`. Then, we can try to do the same again. `c` is another object that we are implicitly stringifying. So then, `a["object Object"] = 456`. - -Then, we log `a[b]`, which is actually `a["object Object"]`. We just set that to `456`, so it returns `456`. - -

-
- ---- - -###### 30. What's the output? - -```javascript -const foo = () => console.log('First'); -const bar = () => setTimeout(() => console.log('Second')); -const baz = () => console.log('Third'); - -bar(); -foo(); -baz(); -``` - -- A: `First` `Second` `Third` -- B: `First` `Third` `Second` -- C: `Second` `First` `Third` -- D: `Second` `Third` `First` - -
Answer -

- -#### Answer: B - -We have a `setTimeout` function and invoked it first. Yet, it was logged last. - -This is because in browsers, we don't just have the runtime engine, we also have something called a `WebAPI`. The `WebAPI` gives us the `setTimeout` function to start with, and for example the DOM. - -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. - - - -Now, `foo` gets invoked, and `"First"` is being logged. - - - -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. - - - -The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the _queue_. - - - -This is where an event loop starts to work. An **event loop** looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack. - - - -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. - -

-
- ---- - -###### 31. What is the event.target when clicking the button? - -```html -
-
- -
-
-``` - -- A: Outer `div` -- B: Inner `div` -- C: `button` -- D: An array of all nested elements. - -
Answer -

- -#### Answer: C - -The deepest nested element that caused the event is the target of the event. You can stop bubbling by `event.stopPropagation` - -

-
- ---- - -###### 32. When you click the paragraph, what's the logged output? - -```html -
-

- Click here! -

-
-``` - -- A: `p` `div` -- B: `div` `p` -- C: `p` -- D: `div` - -
Answer -

- -#### Answer: A - -If we click `p`, we see two logs: `p` and `div`. During event propagation, there are 3 phases: capturing, target, and bubbling. By default, event handlers are executed in the bubbling phase (unless you set `useCapture` to `true`). It goes from the deepest nested element outwards. - -

-
- ---- - -###### 33. What's the output? - -```javascript -const person = { name: 'Lydia' }; - -function sayHi(age) { - return `${this.name} is ${age}`; -} - -console.log(sayHi.call(person, 21)); -console.log(sayHi.bind(person, 21)); -``` - -- A: `undefined is 21` `Lydia is 21` -- B: `function` `function` -- C: `Lydia is 21` `Lydia is 21` -- D: `Lydia is 21` `function` - -
Answer -

- -#### Answer: D - -With both, we can pass the object to which we want the `this` keyword to refer to. However, `.call` is also _executed immediately_! - -`.bind.` returns a _copy_ of the function, but with a bound context! It is not executed immediately. - -

-
- ---- - -###### 34. What's the output? - -```javascript -function sayHi() { - return (() => 0)(); -} - -console.log(typeof sayHi()); -``` - -- A: `"object"` -- B: `"number"` -- C: `"function"` -- D: `"undefined"` - -
Answer -

- -#### Answer: B - -The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. - -FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. - -

-
- ---- - -###### 35. Which of these values are falsy? - -```javascript -0; -new Number(0); -(''); -(' '); -new Boolean(false); -undefined; -``` - -- A: `0`, `''`, `undefined` -- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` -- C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: All of them are falsy - -
Answer -

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

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

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

-
- ---- - -###### 37. What's the output? - -```javascript -const numbers = [1, 2, 3]; -numbers[10] = 11; -console.log(numbers); -``` - -- A: `[1, 2, 3, 7 x null, 11]` -- B: `[1, 2, 3, 11]` -- C: `[1, 2, 3, 7 x empty, 11]` -- D: `SyntaxError` - -
Answer -

- -#### Answer: C - -When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: - -`[1, 2, 3, 7 x empty, 11]` - -depending on where you run it (it's different for every browser, node, etc.) - -

-
- ---- - -###### 38. What's the output? - -```javascript -(() => { - let x, y; - try { - throw new Error(); - } catch (x) { - (x = 1), (y = 2); - console.log(x); - } - console.log(x); - console.log(y); -})(); -``` - -- A: `1` `undefined` `2` -- B: `undefined` `undefined` `undefined` -- C: `1` `1` `2` -- D: `1` `undefined` `undefined` - -
Answer -

- -#### Answer: A - -The `catch` block receives the argument `x`. This is not the same `x` as the variable when we pass arguments. This variable `x` is block-scoped. - -Later, we set this block-scoped variable equal to `1`, and set the value of the variable `y`. Now, we log the block-scoped variable `x`, which is equal to `1`. - -Outside of the `catch` block, `x` is still `undefined`, and `y` is `2`. When we want to `console.log(x)` outside of the `catch` block, it returns `undefined`, and `y` returns `2`. - -

-
- ---- - -###### 39. Everything in JavaScript is either a... - -- A: primitive or object -- B: function or object -- C: trick question! only objects -- D: number or object - -
Answer -

- -#### Answer: A - -JavaScript only has primitive types and objects. - -Primitive types are `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, and `symbol`. - -What differentiates a primitive from an object is that primitives do not have any properties or methods; however, you'll note that `'foo'.toUpperCase()` evaluates to `'FOO'` and does not result in a `TypeError`. This is because when you try to access a property or method on a primitive like a string, JavaScript will implicitly wrap the object using one of the wrapper classes, i.e. `String`, and then immediately discard the wrapper after the expression evaluates. All primitives except for `null` and `undefined` exhibit this behaviour. - -

-
- ---- - -###### 40. What's the output? - -```javascript -[[0, 1], [2, 3]].reduce( - (acc, cur) => { - return acc.concat(cur); - }, - [1, 2], -); -``` - -- A: `[0, 1, 2, 3, 1, 2]` -- B: `[6, 1, 2]` -- C: `[1, 2, 0, 1, 2, 3]` -- D: `[1, 2, 6]` - -
Answer -

- -#### Answer: C - -`[1, 2]` is our initial value. This is the value we start with, and the value of the very first `acc`. During the first round, `acc` is `[1,2]`, and `cur` is `[0, 1]`. We concatenate them, which results in `[1, 2, 0, 1]`. - -Then, `[1, 2, 0, 1]` is `acc` and `[2, 3]` is `cur`. We concatenate them, and get `[1, 2, 0, 1, 2, 3]` - -

-
- ---- - -###### 41. What's the output? - -```javascript -!!null; -!!''; -!!1; -``` - -- A: `false` `true` `false` -- B: `false` `false` `true` -- C: `false` `true` `true` -- D: `true` `true` `false` - -
Answer -

- -#### Answer: B - -`null` is falsy. `!null` returns `true`. `!true` returns `false`. - -`""` is falsy. `!""` returns `true`. `!true` returns `false`. - -`1` is truthy. `!1` returns `false`. `!false` returns `true`. - -

-
- ---- - -###### 42. What does the `setInterval` method return in the browser? - -```javascript -setInterval(() => console.log('Hi'), 1000); -``` - -- A: a unique id -- B: the amount of milliseconds specified -- C: the passed function -- D: `undefined` - -
Answer -

- -#### Answer: A - -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. - -

-
- ---- - -###### 43. What does this return? - -```javascript -[...'Lydia']; -``` - -- A: `["L", "y", "d", "i", "a"]` -- B: `["Lydia"]` -- C: `[[], "Lydia"]` -- D: `[["L", "y", "d", "i", "a"]]` - -
Answer -

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

-
- ---- - -###### 44. What's the output? - -```javascript -function* generator(i) { - yield i; - yield i * 2; -} - -const gen = generator(10); - -console.log(gen.next().value); -console.log(gen.next().value); -``` - -- A: `[0, 10], [10, 20]` -- B: `20, 20` -- C: `10, 20` -- D: `0, 10 and 10, 20` - -
Answer -

- -#### Answer: C - -Regular functions cannot be stopped mid-way after invocation. However, a generator function can be "stopped" midway, and later continue from where it stopped. Every time a generator function encounters a `yield` keyword, the function yields the value specified after it. Note that the generator function in that case doesn’t _return_ the value, it _yields_ the value. - -First, we initialize the generator function with `i` equal to `10`. We invoke the generator function using the `next()` method. The first time we invoke the generator function, `i` is equal to `10`. It encounters the first `yield` keyword: it yields the value of `i`. The generator is now "paused", and `10` gets logged. - -Then, we invoke the function again with the `next()` method. It starts to continue where it stopped previously, still with `i` equal to `10`. Now, it encounters the next `yield` keyword, and yields `i * 2`. `i` is equal to `10`, so it returns `10 * 2`, which is `20`. This results in `10, 20`. - -

-
- ---- - -###### 45. What does this return? - -```javascript -const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, 'one'); -}); - -const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, 'two'); -}); - -Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); -``` - -- A: `"one"` -- B: `"two"` -- C: `"two" "one"` -- D: `"one" "two"` - -
Answer -

- -#### Answer: B - -When we pass multiple promises to the `Promise.race` method, it resolves/rejects the _first_ promise that resolves/rejects. To the `setTimeout` method, we pass a timer: 500ms for the first promise (`firstPromise`), and 100ms for the second promise (`secondPromise`). This means that the `secondPromise` resolves first with the value of `'two'`. `res` now holds the value of `'two'`, which gets logged. - -

-
- ---- - -###### 46. What's the output? - -```javascript -let person = { name: 'Lydia' }; -const members = [person]; -person = null; - -console.log(members); -``` - -- A: `null` -- B: `[null]` -- C: `[{}]` -- D: `[{ name: "Lydia" }]` - -
Answer -

- -#### Answer: D - -First, we declare a variable `person` with the value of an object that has a `name` property. - - - -Then, we declare a variable called `members`. We set the first element of that array equal to the value of the `person` variable. Objects interact by _reference_ when setting them equal to each other. When you assign a reference from one variable to another, you make a _copy_ of that reference. (note that they don't have the _same_ reference!) - - - -Then, we set the variable `person` equal to `null`. - - - -We are only modifying the value of the `person` variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in `members` still holds its reference to the original object. When we log the `members` array, the first element still holds the value of the object, which gets logged. - -

-
- ---- - -###### 47. What's the output? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -for (const item in person) { - console.log(item); -} -``` - -- A: `{ name: "Lydia" }, { age: 21 }` -- B: `"name", "age"` -- C: `"Lydia", 21` -- D: `["name", "Lydia"], ["age", 21]` - -
Answer -

- -#### Answer: B - -With a `for-in` loop, we can iterate through object keys, in this case `name` and `age`. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of `item` equal to the current key it’s iterating over. First, `item` is equal to `name`, and gets logged. Then, `item` is equal to `age`, which gets logged. - -

-
- ---- - -###### 48. What's the output? - -```javascript -console.log(3 + 4 + '5'); -``` - -- A: `"345"` -- B: `"75"` -- C: `12` -- D: `"12"` - -
Answer -

- -#### Answer: B - -Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the _same_ precedence. We only have one type of operator: `+`. For addition, the associativity is left-to-right. - -`3 + 4` gets evaluated first. This results in the number `7`. - -`7 + '5'` results in `"75"` because of coercion. JavaScript converts the number `7` into a string, see question 15. We can concatenate two strings using the `+`operator. `"7" + "5"` results in `"75"`. - -

-
- ---- - -###### 49. What's the value of `num`? - -```javascript -const num = parseInt('7*6', 10); -``` - -- A: `42` -- B: `"42"` -- C: `7` -- D: `NaN` - -
Answer -

- -#### Answer: C - -Only the first numbers in the string is returned. Based on the _radix_ (the second argument in order to specify what type of number we want to parse it to: base 10, hexadecimal, octal, binary, etc.), the `parseInt` checks whether the characters in the string are valid. Once it encounters a character that isn't a valid number in the radix, it stops parsing and ignores the following characters. - -`*` is not a valid number. It only parses `"7"` into the decimal `7`. `num` now holds the value of `7`. - -

-
- ---- - -###### 50. What's the output`? - -```javascript -[1, 2, 3].map(num => { - if (typeof num === 'number') return; - return num * 2; -}); -``` - -- A: `[]` -- B: `[null, null, null]` -- C: `[undefined, undefined, undefined]` -- D: `[ 3 x empty ]` - -
Answer -

- -#### Answer: C - -When mapping over the array, the value of `num` is equal to the element it’s currently looping over. In this case, the elements are numbers, so the condition of the if statement `typeof num === "number"` returns `true`. The map function creates a new array and inserts the values returned from the function. - -However, we don’t return a value. When we don’t return a value from the function, the function returns `undefined`. For every element in the array, the function block gets called, so for each element we return `undefined`. - -

-
- ---- - -###### 51. What's the output? - -```javascript -function getInfo(member, year) { - member.name = 'Lydia'; - year = '1998'; -} - -const person = { name: 'Sarah' }; -const birthYear = '1997'; - -getInfo(person, birthYear); - -console.log(person, birthYear); -``` - -- A: `{ name: "Lydia" }, "1997"` -- B: `{ name: "Sarah" }, "1998"` -- C: `{ name: "Lydia" }, "1998"` -- D: `{ name: "Sarah" }, "1997"` - -
Answer -

- -#### Answer: A - -Arguments are passed by _value_, unless their value is an object, then they're passed by _reference_. `birthYear` is passed by value, since it's a string, not an object. When we pass arguments by value, a _copy_ of that value is created (see question 46). - -The variable `birthYear` has a reference to the value `"1997"`. The argument `year` also has a reference to the value `"1997"`, but it's not the same value as `birthYear` has a reference to. When we update the value of `year` by setting `year` equal to `"1998"`, we are only updating the value of `year`. `birthYear` is still equal to `"1997"`. - -The value of `person` is an object. The argument `member` has a (copied) reference to the _same_ object. When we modify a property of the object `member` has a reference to, the value of `person` will also be modified, since they both have a reference to the same object. `person`'s `name` property is now equal to the value `"Lydia"` - -

-
- ---- - -###### 52. What's the output? - -```javascript -function greeting() { - throw 'Hello world!'; -} - -function sayHi() { - try { - const data = greeting(); - console.log('It worked!', data); - } catch (e) { - console.log('Oh no an error:', e); - } -} - -sayHi(); -``` - -- A: `It worked! Hello world!` -- B: `Oh no an error: undefined` -- C: `SyntaxError: can only throw Error objects` -- D: `Oh no an error: Hello world!` - -
Answer -

- -#### Answer: D - -With the `throw` statement, we can create custom errors. With this statement, you can throw exceptions. An exception can be a string, a number, a boolean or an object. In this case, our exception is the string `'Hello world'`. - -With the `catch` statement, we can specify what to do if an exception is thrown in the `try` block. An exception is thrown: the string `'Hello world'`. `e` is now equal to that string, which we log. This results in `'Oh an error: Hello world'`. - -

-
- ---- - -###### 53. What's the output? - -```javascript -function Car() { - this.make = 'Lamborghini'; - return { make: 'Maserati' }; -} - -const myCar = new Car(); -console.log(myCar.make); -``` - -- A: `"Lamborghini"` -- B: `"Maserati"` -- C: `ReferenceError` -- D: `TypeError` - -
Answer -

- -#### Answer: B - -When you return a property, the value of the property is equal to the _returned_ value, not the value set in the constructor function. We return the string `"Maserati"`, so `myCar.make` is equal to `"Maserati"`. - -

-
- ---- - -###### 54. What's the output? - -```javascript -(() => { - let x = (y = 10); -})(); - -console.log(typeof x); -console.log(typeof y); -``` - -- A: `"undefined", "number"` -- B: `"number", "number"` -- C: `"object", "number"` -- D: `"number", "undefined"` - -
Answer -

- -#### Answer: A - -`let x = y = 10;` is actually shorthand for: - -```javascript -y = 10; -let x = y; -``` - -When we set `y` equal to `10`, we actually add a property `y` to the global object (`window` in browser, `global` in Node). In a browser, `window.y` is now equal to `10`. - -Then, we declare a variable `x` with the value of `y`, which is `10`. Variables declared with the `let` keyword are _block scoped_, they are only defined within the block they're declared in; the immediately-invoked function (IIFE) in this case. When we use the `typeof` operator, the operand `x` is not defined: we are trying to access `x` outside of the block it's declared in. This means that `x` is not defined. Values who haven't been assigned a value or declared are of type `"undefined"`. `console.log(typeof x)` returns `"undefined"`. - -However, we created a global variable `y` when setting `y` equal to `10`. This value is accessible anywhere in our code. `y` is defined, and holds a value of type `"number"`. `console.log(typeof y)` returns `"number"`. - -

-
- ---- - -###### 55. What's the output? - -```javascript -class Dog { - constructor(name) { - this.name = name; - } -} - -Dog.prototype.bark = function() { - console.log(`Woof I am ${this.name}`); -}; - -const pet = new Dog('Mara'); - -pet.bark(); - -delete Dog.prototype.bark; - -pet.bark(); -``` - -- A: `"Woof I am Mara"`, `TypeError` -- B: `"Woof I am Mara"`, `"Woof I am Mara"` -- C: `"Woof I am Mara"`, `undefined` -- D: `TypeError`, `TypeError` - -
Answer -

- -#### Answer: A - -We can delete properties from objects using the `delete` keyword, also on the prototype. By deleting a property on the prototype, it is not available anymore in the prototype chain. In this case, the `bark` function is not available anymore on the prototype after `delete Dog.prototype.bark`, yet we still try to access it. - -When we try to invoke something that is not a function, a `TypeError` is thrown. In this case `TypeError: pet.bark is not a function`, since `pet.bark` is `undefined`. - -

-
- ---- - -###### 56. What's the output? - -```javascript -const set = new Set([1, 1, 2, 3, 4]); - -console.log(set); -``` - -- A: `[1, 1, 2, 3, 4]` -- B: `[1, 2, 3, 4]` -- C: `{1, 1, 2, 3, 4}` -- D: `{1, 2, 3, 4}` - -
Answer -

- -#### Answer: D - -The `Set` object is a collection of _unique_ values: a value can only occur once in a set. - -We passed the iterable `[1, 1, 2, 3, 4]` with a duplicate value `1`. Since we cannot have two of the same values in a set, one of them is removed. This results in `{1, 2, 3, 4}`. - -

-
- ---- - -###### 57. What's the output? - -```javascript -// counter.js -let counter = 10; -export default counter; -``` - -```javascript -// index.js -import myCounter from './counter'; - -myCounter += 1; - -console.log(myCounter); -``` - -- A: `10` -- B: `11` -- C: `Error` -- D: `NaN` - -
Answer -

- -#### Answer: C - -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. - -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified. - -

-
- ---- - -###### 58. What's the output? - -```javascript -const name = 'Lydia'; -age = 21; - -console.log(delete name); -console.log(delete age); -``` - -- A: `false`, `true` -- B: `"Lydia"`, `21` -- C: `true`, `true` -- D: `undefined`, `undefined` - -
Answer -

- -#### Answer: A - -The `delete` operator returns a boolean value: `true` on a successful deletion, else it'll return `false`. However, variables declared with the `var`, `const` or `let` keyword cannot be deleted using the `delete` operator. - -The `name` variable was declared with a `const` keyword, so its deletion is not successful: `false` is returned. When we set `age` equal to `21`, we actually added a property called `age` to the global object. You can successfully delete properties from objects this way, also the global object, so `delete age` returns `true`. - -

-
- ---- - -###### 59. What's the output? - -```javascript -const numbers = [1, 2, 3, 4, 5]; -const [y] = numbers; - -console.log(y); -``` - -- A: `[[1, 2, 3, 4, 5]]` -- B: `[1, 2, 3, 4, 5]` -- C: `1` -- D: `[1]` - -
Answer -

- -#### Answer: C - -We can unpack values from arrays or properties from objects through destructuring. For example: - -```javascript -[a, b] = [1, 2]; -``` - - - -The value of `a` is now `1`, and the value of `b` is now `2`. What we actually did in the question, is: - -```javascript -[y] = [1, 2, 3, 4, 5]; -``` - - - -This means that the value of `y` is equal to the first value in the array, which is the number `1`. When we log `y`, `1` is returned. - -

-
- ---- - -###### 60. What's the output? - -```javascript -const user = { name: 'Lydia', age: 21 }; -const admin = { admin: true, ...user }; - -console.log(admin); -``` - -- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` -- B: `{ admin: true, name: "Lydia", age: 21 }` -- C: `{ admin: true, user: ["Lydia", 21] }` -- D: `{ admin: true }` - -
Answer -

- -#### Answer: B - -It's possible to combine objects using the spread operator `...`. It lets you create copies of the key/value pairs of one object, and add them to another object. In this case, we create copies of the `user` object, and add them to the `admin` object. The `admin` object now contains the copied key/value pairs, which results in `{ admin: true, name: "Lydia", age: 21 }`. - -

-
- ---- - -###### 61. What's the output? - -```javascript -const person = { name: 'Lydia' }; - -Object.defineProperty(person, 'age', { value: 21 }); - -console.log(person); -console.log(Object.keys(person)); -``` - -- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` -- B: `{ name: "Lydia", age: 21 }`, `["name"]` -- C: `{ name: "Lydia"}`, `["name", "age"]` -- D: `{ name: "Lydia"}`, `["age"]` - -
Answer -

- -#### Answer: B - -With the `defineProperty` method, we can add new properties to an object, or modify existing ones. When we add a property to an object using the `defineProperty` method, they are by default _not enumerable_. The `Object.keys` method returns all _enumerable_ property names from an object, in this case only `"name"`. - -Properties added using the `defineProperty` method are immutable by default. You can override this behavior using the `writable`, `configurable` and `enumerable` properties. This way, the `defineProperty` method gives you a lot more control over the properties you're adding to an object. - -

-
- ---- - -###### 62. What's the output? - -```javascript -const settings = { - username: 'lydiahallie', - level: 19, - health: 90, -}; - -const data = JSON.stringify(settings, ['level', 'health']); -console.log(data); -``` - -- A: `"{"level":19, "health":90}"` -- B: `"{"username": "lydiahallie"}"` -- C: `"["level", "health"]"` -- D: `"{"username": "lydiahallie", "level":19, "health":90}"` - -
Answer -

- -#### Answer: A - -The second argument of `JSON.stringify` is the _replacer_. The replacer can either be a function or an array, and lets you control what and how the values should be stringified. - -If the replacer is an _array_, only the property names included in the array will be added to the JSON string. In this case, only the properties with the names `"level"` and `"health"` are included, `"username"` is excluded. `data` is now equal to `"{"level":19, "health":90}"`. - -If the replacer is a _function_, this function gets called on every property in the object you're stringifying. The value returned from this function will be the value of the property when it's added to the JSON string. If the value is `undefined`, this property is excluded from the JSON string. - -

-
- ---- - -###### 63. What's the output? - -```javascript -let num = 10; - -const increaseNumber = () => num++; -const increasePassedNumber = number => number++; - -const num1 = increaseNumber(); -const num2 = increasePassedNumber(num1); - -console.log(num1); -console.log(num2); -``` - -- A: `10`, `10` -- B: `10`, `11` -- C: `11`, `11` -- D: `11`, `12` - -
Answer -

- -#### Answer: A - -The unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `num1` is `10`, since the `increaseNumber` function first returns the value of `num`, which is `10`, and only increments the value of `num` afterwards. - -`num2` is `10`, since we passed `num1` to the `increasePassedNumber`. `number` is equal to `10`(the value of `num1`. Again, the unary operator `++` _first returns_ the value of the operand, _then increments_ the value of the operand. The value of `number` is `10`, so `num2` is equal to `10`. - -

-
- ---- - -###### 64. What's the output? - -```javascript -const value = { number: 10 }; - -const multiply = (x = { ...value }) => { - console.log((x.number *= 2)); -}; - -multiply(); -multiply(); -multiply(value); -multiply(value); -``` - -- A: `20`, `40`, `80`, `160` -- B: `20`, `40`, `20`, `40` -- C: `20`, `20`, `20`, `40` -- D: `NaN`, `NaN`, `20`, `40` - -
Answer -

- -#### Answer: C - -In ES6, we can initialize parameters with a default value. The value of the parameter will be the default value, if no other value has been passed to the function, or if the value of the parameter is `"undefined"`. In this case, we spread the properties of the `value` object into a new object, so `x` has the default value of `{ number: 10 }`. - -The default argument is evaluated at _call time_! Every time we call the function, a _new_ object is created. We invoke the `multiply` function the first two times without passing a value: `x` has the default value of `{ number: 10 }`. We then log the multiplied value of that number, which is `20`. - -The third time we invoke multiply, we do pass an argument: the object called `value`. The `*=` operator is actually shorthand for `x.number = x.number * 2`: we modify the value of `x.number`, and log the multiplied value `20`. - -The fourth time, we pass the `value` object again. `x.number` was previously modified to `20`, so `x.number *= 2` logs `40`. - -

-
- ---- - -###### 65. What's the output? - -```javascript -[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); -``` - -- A: `1` `2` and `3` `3` and `6` `4` -- B: `1` `2` and `2` `3` and `3` `4` -- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` -- D: `1` `2` and `undefined` `3` and `undefined` `4` - -
Answer -

- -#### Answer: D - -The first argument that the `reduce` method receives is the _accumulator_, `x` in this case. The second argument is the _current value_, `y`. With the reduce method, we execute a callback function on every element in the array, which could ultimately result in one single value. - -In this example, we are not returning any values, we are simply logging the values of the accumulator and the current value. - -The value of the accumulator is equal to the previously returned value of the callback function. If you don't pass the optional `initialValue` argument to the `reduce` method, the accumulator is equal to the first element on the first call. - -On the first call, the accumulator (`x`) is `1`, and the current value (`y`) is `2`. We don't return from the callback function, we log the accumulator and current value: `1` and `2` get logged. - -If you don't return a value from a function, it returns `undefined`. On the next call, the accumulator is `undefined`, and the current value is `3`. `undefined` and `3` get logged. - -On the fourth call, we again don't return from the callback function. The accumulator is again `undefined`, and the current value is `4`. `undefined` and `4` get logged. - -

-
- ---- - -###### 66. With which constructor can we successfully extend the `Dog` class? - -```javascript -class Dog { - constructor(name) { - this.name = name; - } -}; - -class Labrador extends Dog { - // 1 - constructor(name, size) { - this.size = size; - } - // 2 - constructor(name, size) { - super(name); - this.size = size; - } - // 3 - constructor(size) { - super(name); - this.size = size; - } - // 4 - constructor(name, size) { - this.name = name; - this.size = size; - } - -}; -``` - -- A: 1 -- B: 2 -- C: 3 -- D: 4 - -
Answer -

- -#### Answer: B - -In a derived class, you cannot access the `this` keyword before calling `super`. If you try to do that, it will throw a ReferenceError: 1 and 4 would throw a reference error. - -With the `super` keyword, we call that parent class's constructor with the given arguments. The parent's constructor receives the `name` argument, so we need to pass `name` to `super`. - -The `Labrador` class receives two arguments, `name` since it extends `Dog`, and `size` as an extra property on the `Labrador` class. They both need to be passed to the constructor function on `Labrador`, which is done correctly using constructor 2. - -

-
- ---- - -###### 67. What's the output? - -```javascript -// index.js -console.log('running index.js'); -import { sum } from './sum.js'; -console.log(sum(1, 2)); - -// sum.js -console.log('running sum.js'); -export const sum = (a, b) => a + b; -``` - -- A: `running index.js`, `running sum.js`, `3` -- B: `running sum.js`, `running index.js`, `3` -- C: `running sum.js`, `3`, `running index.js` -- D: `running index.js`, `undefined`, `running sum.js` - -
Answer -

- -#### Answer: B - -With the `import` keyword, all imported modules are _pre-parsed_. This means that the imported modules get run _first_, the code in the file which imports the module gets executed _after_. - -This is a difference between `require()` in CommonJS and `import`! With `require()`, you can load dependencies on demand while the code is being run. If we would have used `require` instead of `import`, `running index.js`, `running sum.js`, `3` would have been logged to the console. - -

-
- ---- - -###### 68. What's the output? - -```javascript -console.log(Number(2) === Number(2)); -console.log(Boolean(false) === Boolean(false)); -console.log(Symbol('foo') === Symbol('foo')); -``` - -- A: `true`, `true`, `false` -- B: `false`, `true`, `false` -- C: `true`, `false`, `true` -- D: `true`, `true`, `true` - -
Answer -

- -#### Answer: A - -Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first `Symbol('foo')`, and the second `Symbol('foo')`. These two values are unique and not equal to each other, `Symbol('foo') === Symbol('foo')` returns `false`. - -

-
- ---- - -###### 69. What's the output? - -```javascript -const name = 'Lydia Hallie'; -console.log(name.padStart(13)); -console.log(name.padStart(2)); -``` - -- A: `"Lydia Hallie"`, `"Lydia Hallie"` -- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) -- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) -- D: `"Lydia Hallie"`, `"Lyd"`, - -
Answer -

- -#### Answer: C - -With the `padStart` method, we can add padding to the beginning of a string. The value passed to this method is the _total_ length of the string together with the padding. The string `"Lydia Hallie"` has a length of `12`. `name.padStart(13)` inserts 1 space at the start of the string, because 12 + 1 is 13. - -If the argument passed to the `padStart` method is smaller than the length of the array, no padding will be added. - -

-
- ---- - -###### 70. What's the output? - -```javascript -console.log('🥑' + '💻'); -``` - -- A: `"🥑💻"` -- B: `257548` -- C: A string containing their code points -- D: Error - -
Answer -

- -#### Answer: A - -With the `+` operator, you can concatenate strings. In this case, we are concatenating the string `"🥑"` with the string `"💻"`, resulting in `"🥑💻"`. - -

-
- ---- - -###### 71. How can we log the values that are commented out after the console.log statement? - -```javascript -function* startGame() { - const answer = yield 'Do you love JavaScript?'; - if (answer !== 'Yes') { - return "Oh wow... Guess we're gone here"; - } - return 'JavaScript loves you back ❤️'; -} - -const game = startGame(); -console.log(/* 1 */); // Do you love JavaScript? -console.log(/* 2 */); // JavaScript loves you back ❤️ -``` - -- A: `game.next("Yes").value` and `game.next().value` -- B: `game.next.value("Yes")` and `game.next.value()` -- C: `game.next().value` and `game.next("Yes").value` -- D: `game.next.value()` and `game.next.value("Yes")` - -
Answer -

- -#### Answer: C - -A generator function "pauses" its execution when it sees the `yield` keyword. First, we have to let the function yield the string "Do you love JavaScript?", which can be done by calling `game.next().value`. - -Every line is executed, until it finds the first `yield` keyword. There is a `yield` keyword on the first line within the function: the execution stops with the first yield! _This means that the variable `answer` is not defined yet!_ - -When we call `game.next("Yes").value`, the previous `yield` is replaced with the value of the parameters passed to the `next()` function, `"Yes"` in this case. The value of the variable `answer` is now equal to `"Yes"`. The condition of the if-statement returns `false`, and `JavaScript loves you back ❤️` gets logged. - -

-
- ---- - -###### 72. What's the output? - -```javascript -console.log(String.raw`Hello\nworld`); -``` - -- A: `Hello world!` -- B: `Hello`
     `world` -- C: `Hello\nworld` -- D: `Hello\n`
     `world` - -
Answer -

- -#### Answer: C - -`String.raw` returns a string where the escapes (`\n`, `\v`, `\t` etc.) are ignored! Backslashes can be an issue since you could end up with something like: - -`` const path = `C:\Documents\Projects\table.html` `` - -Which would result in: - -`"C:DocumentsProjects able.html"` - -With `String.raw`, it would simply ignore the escape and print: - -`C:\Documents\Projects\table.html` - -In this case, the string is `Hello\nworld`, which gets logged. - -

-
- ---- - -###### 73. What's the output? - -```javascript -async function getData() { - return await Promise.resolve('I made it!'); -} - -const data = getData(); -console.log(data); -``` - -- A: `"I made it!"` -- B: `Promise {: "I made it!"}` -- C: `Promise {}` -- D: `undefined` - -
Answer -

- -#### Answer: C - -An async function always returns a promise. The `await` still has to wait for the promise to resolve: a pending promise gets returned when we call `getData()` in order to set `data` equal to it. - -If we wanted to get access to the resolved value `"I made it"`, we could have used the `.then()` method on `data`: - -`data.then(res => console.log(res))` - -This would've logged `"I made it!"` - -

-
- ---- - -###### 74. What's the output? - -```javascript -function addToList(item, list) { - return list.push(item); -} - -const result = addToList('apple', ['banana']); -console.log(result); -``` - -- A: `['apple', 'banana']` -- B: `2` -- C: `true` -- D: `undefined` - -
Answer -

- -#### Answer: B - -The `.push()` method returns the _length_ of the new array! Previously, the array contained one element (the string `"banana"`) and had a length of `1`. After adding the string `"apple"` to the array, the array contains two elements, and has a length of `2`. This gets returned from the `addToList` function. - -The `push` method modifies the original array. If you wanted to return the _array_ from the function rather than the _length of the array_, you should have returned `list` after pushing `item` to it. - -

-
- ---- - -###### 75. What's the output? - -```javascript -const box = { x: 10, y: 20 }; - -Object.freeze(box); - -const shape = box; -shape.x = 100; - -console.log(shape); -``` - -- A: `{ x: 100, y: 20 }` -- B: `{ x: 10, y: 20 }` -- C: `{ x: 100 }` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -`Object.freeze` makes it impossible to add, remove, or modify properties of an object (unless the property's value is another object). - -When we create the variable `shape` and set it equal to the frozen object `box`, `shape` also refers to a frozen object. You can check whether an object is frozen by using `Object.isFrozen`. In this case, `Object.isFrozen(shape)` returns true, since the variable `shape` has a reference to a frozen object. - -Since `shape` is frozen, and since the value of `x` is not an object, we cannot modify the property `x`. `x` is still equal to `10`, and `{ x: 10, y: 20 }` gets logged. - -

-
- ---- - -###### 76. What's the output? - -```javascript -const { name: myName } = { name: 'Lydia' }; - -console.log(name); -``` - -- A: `"Lydia"` -- B: `"myName"` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

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

-
- ---- - -###### 77. Is this a pure function? - -```javascript -function sum(a, b) { - return a + b; -} -``` - -- A: Yes -- B: No - -
Answer -

- -#### Answer: A - -A pure function is a function that _always_ returns the same result, if the same arguments are passed. - -The `sum` function always returns the same result. If we pass `1` and `2`, it will _always_ return `3` without side effects. If we pass `5` and `10`, it will _always_ return `15`, and so on. This is the definition of a pure function. - -

-
- ---- - -###### 78. What is the output? - -```javascript -const add = () => { - const cache = {}; - return num => { - if (num in cache) { - return `From cache! ${cache[num]}`; - } else { - const result = num + 10; - cache[num] = result; - return `Calculated! ${result}`; - } - }; -}; - -const addFunction = add(); -console.log(addFunction(10)); -console.log(addFunction(10)); -console.log(addFunction(5 * 2)); -``` - -- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` -- B: `Calculated! 20` `From cache! 20` `Calculated! 20` -- C: `Calculated! 20` `From cache! 20` `From cache! 20` -- D: `Calculated! 20` `From cache! 20` `Error` - -
Answer -

- -#### Answer: C - -The `add` function is a _memoized_ function. With memoization, we can cache the results of a function in order to speed up its execution. In this case, we create a `cache` object that stores the previously returned values. - -If we call the `addFunction` function again with the same argument, it first checks whether it has already gotten that value in its cache. If that's the case, the caches value will be returned, which saves on execution time. Else, if it's not cached, it will calculate the value and store it afterwards. - -We call the `addFunction` function three times with the same value: on the first invocation, the value of the function when `num` is equal to `10` isn't cached yet. The condition of the if-statement `num in cache` returns `false`, and the else block gets executed: `Calculated! 20` gets logged, and the value of the result gets added to the cache object. `cache` now looks like `{ 10: 20 }`. - -The second time, the `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. - -The third time, we pass `5 * 2` to the function which gets evaluated to `10`. The `cache` object contains the value that gets returned for `10`. The condition of the if-statement `num in cache` returns `true`, and `'From cache! 20'` gets logged. - -

-
- ---- - -###### 79. What is the output? - -```javascript -const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; - -for (let item in myLifeSummedUp) { - console.log(item); -} - -for (let item of myLifeSummedUp) { - console.log(item); -} -``` - -- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` -- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` -- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` -- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` - -
Answer -

- -#### Answer: A - -With a _for-in_ loop, we can iterate over **enumerable** properties. In an array, the enumerable properties are the "keys" of array elements, which are actually their indexes. You could see an array as: - -`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` - -Where the keys are the enumerable properties. `0` `1` `2` `3` get logged. - -With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable. When we iterate over the array, the variable "item" is equal to the element it's currently iterating over, `"☕"` `"💻"` `"🍷"` `"🍫"` get logged. - -

-
- ---- - -###### 80. What is the output? - -```javascript -const list = [1 + 2, 1 * 2, 1 / 2]; -console.log(list); -``` - -- A: `["1 + 2", "1 * 2", "1 / 2"]` -- B: `["12", 2, 0.5]` -- C: `[3, 2, 0.5]` -- D: `[1, 1, 1]` - -
Answer -

- -#### Answer: C - -Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. - -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. - -

-
- ---- - -###### 81. What is the output? - -```javascript -function sayHi(name) { - return `Hi there, ${name}`; -} - -console.log(sayHi()); -``` - -- A: `Hi there,` -- B: `Hi there, undefined` -- C: `Hi there, null` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -By default, arguments have the value of `undefined`, unless a value has been passed to the function. In this case, we didn't pass a value for the `name` argument. `name` is equal to `undefined` which gets logged. - -In ES6, we can overwrite this default `undefined` value with default parameters. For example: - -`function sayHi(name = "Lydia") { ... }` - -In this case, if we didn't pass a value or if we passed `undefined`, `name` would always be equal to the string `Lydia` - -

-
- ---- - -###### 82. What is the output? - -```javascript -var status = '😎'; - -setTimeout(() => { - const status = '😍'; - - const data = { - status: '🥑', - getStatus() { - return this.status; - }, - }; - - console.log(data.getStatus()); - console.log(data.getStatus.call(this)); -}, 0); -``` - -- A: `"🥑"` and `"😍"` -- B: `"🥑"` and `"😎"` -- C: `"😍"` and `"😎"` -- D: `"😎"` and `"😎"` - -
Answer -

- -#### Answer: B - -The value of the `this` keyword is dependent on where you use it. In a **method**, like the `getStatus` method, the `this` keyword refers to _the object that the method belongs to_. The method belongs to the `data` object, so `this` refers to the `data` object. When we log `this.status`, the `status` property on the `data` object gets logged, which is `"🥑"`. - -With the `call` method, we can change the object to which the `this` keyword refers. In **functions**, the `this` keyword refers to the _the object that the function belongs to_. We declared the `setTimeout` function on the _global object_, so within the `setTimeout` function, the `this` keyword refers to the _global object_. On the global object, there is a variable called _status_ with the value of `"😎"`. When logging `this.status`, `"😎"` gets logged. - -

-
- ---- - -###### 83. What is the output? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -let city = person.city; -city = 'Amsterdam'; - -console.log(person); -``` - -- A: `{ name: "Lydia", age: 21 }` -- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` -- C: `{ name: "Lydia", age: 21, city: undefined }` -- D: `"Amsterdam"` - -
Answer -

- -#### Answer: A - -We set the variable `city` equal to the value of the property called `city` on the `person` object. There is no property on this object called `city`, so the variable `city` has the value of `undefined`. - -Note that we are _not_ referencing the `person` object itself! We simply set the variable `city` equal to the current value of the `city` property on the `person` object. - -Then, we set `city` equal to the string `"Amsterdam"`. This doesn't change the person object: there is no reference to that object. - -When logging the `person` object, the unmodified object gets returned. - -

-
- ---- - -###### 84. What is the output? - -```javascript -function checkAge(age) { - if (age < 18) { - const message = "Sorry, you're too young."; - } else { - const message = "Yay! You're old enough!"; - } - - return message; -} - -console.log(checkAge(21)); -``` - -- A: `"Sorry, you're too young."` -- B: `"Yay! You're old enough!"` -- C: `ReferenceError` -- D: `undefined` - -
Answer -

- -#### Answer: C - -Variables with the `const` and `let` keyword are _block-scoped_. A block is anything between curly brackets (`{ }`). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it's declared in, a ReferenceError gets thrown. - -

-
- ---- - -###### 85. What kind of information would get logged? - -```javascript -fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); -``` - -- A: The result of the `fetch` method. -- B: The result of the second invocation of the `fetch` method. -- C: The result of the callback in the previous `.then()`. -- D: It would always be undefined. - -
Answer -

- -#### Answer: C - -The value of `res` in the second `.then` is equal to the returned value of the previous `.then`. You can keep chaining `.then`s like this, where the value is passed to the next handler. - -

-
- ---- - -###### 86. Which option is a way to set `hasName` equal to `true`, provided you cannot pass `true` as an argument? - -```javascript -function getName(name) { - const hasName = // -} -``` - -- A: `!!name` -- B: `name` -- C: `new Boolean(name)` -- D: `name.length` - -
Answer -

- -#### Answer: A - -With `!!name`, we determine whether the value of `name` is truthy or falsy. If name is truthy, which we want to test for, `!name` returns `false`. `!false` (which is what `!!name` practically is) returns `true`. - -By setting `hasName` equal to `name`, you set `hasName` equal to whatever value you passed to the `getName` function, not the boolean value `true`. - -`new Boolean(true)` returns an object wrapper, not the boolean value itself. - -`name.length` returns the length of the passed argument, not whether it's `true`. - -

-
- ---- - -###### 87. What's the output? - -```javascript -console.log('I want pizza'[0]); -``` - -- A: `"""` -- B: `"I"` -- C: `SyntaxError` -- D: `undefined` - -
Answer -

- -#### Answer: B - -In order to get an character on a specific index in a string, you can use bracket notation. The first character in the string has index 0, and so on. In this case we want to get the element which index is 0, the character `"I'`, which gets logged. - -Note that this method is not supported in IE7 and below. In that case, use `.charAt()` - -

-
- ---- - -###### 88. What's the output? - -```javascript -function sum(num1, num2 = num1) { - console.log(num1 + num2); -} - -sum(10); -``` - -- A: `NaN` -- B: `20` -- C: `ReferenceError` -- D: `undefined` - -
Answer -

- -#### Answer: B - -You can set a default parameter's value equal to another parameter of the function, as long as they've been defined _before_ the default parameter. We pass the value `10` to the `sum` function. If the `sum` function only receives 1 argument, it means that the value for `num2` is not passed, and the value of `num1` is equal to the passed value `10` in this case. The default value of `num2` is the value of `num1`, which is `10`. `num1 + num2` returns `20`. - -If you're trying to set a default parameter's value equal to a parameter which is defined _after_ (to the right), the parameter's value hasn't been initialized yet, which will throw an error. - -

-
- ---- - -###### 89. What's the output? - -```javascript -// module.js -export default () => 'Hello world'; -export const name = 'Lydia'; - -// index.js -import * as data from './module'; - -console.log(data); -``` - -- A: `{ default: function default(), name: "Lydia" }` -- B: `{ default: function default() }` -- C: `{ default: "Hello world", name: "Lydia" }` -- D: Global object of `module.js` - -
Answer -

- -#### Answer: A - -With the `import * as name` syntax, we import _all exports_ from the `module.js` file into the `index.js` file as a new object called `data` is created. In the `module.js` file, there are two exports: the default export, and a named export. The default export is a function which returns the string `"Hello World"`, and the named export is a variable called `name` which has the value of the string `"Lydia"`. - -The `data` object has a `default` property for the default export, other properties have the names of the named exports and their corresponding values. - -

-
- ---- - -###### 90. What's the output? - -```javascript -class Person { - constructor(name) { - this.name = name; - } -} - -const member = new Person('John'); -console.log(typeof member); -``` - -- A: `"class"` -- B: `"function"` -- C: `"object"` -- D: `"string"` - -
Answer -

- -#### Answer: C - -Classes are syntactical sugar for function constructors. The equivalent of the `Person` class as a function constructor would be: - -```javascript -function Person() { - this.name = name; -} -``` - -Calling a function constructor with `new` results in the creation of an instance of `Person`, `typeof` keyword returns `"object"` for an instance. `typeof member` returns `"object"`. - -

-
- ---- - -###### 91. What's the output? - -```javascript -let newList = [1, 2, 3].push(4); - -console.log(newList.push(5)); -``` - -- A: `[1, 2, 3, 4, 5]` -- B: `[1, 2, 3, 5]` -- C: `[1, 2, 3, 4]` -- D: `Error` - -
Answer -

- -#### Answer: D - -The `.push` method returns the _new length_ of the array, not the array itself! By setting `newList` equal to `[1, 2, 3].push(4)`, we set `newList` equal to the new length of the array: `4`. - -Then, we try to use the `.push` method on `newList`. Since `newList` is the numerical value `4`, we cannot use the `.push` method: a TypeError is thrown. - -

-
- ---- - -###### 92. What's the output? - -```javascript -function giveLydiaPizza() { - return 'Here is pizza!'; -} - -const giveLydiaChocolate = () => - "Here's chocolate... now go hit the gym already."; - -console.log(giveLydiaPizza.prototype); -console.log(giveLydiaChocolate.prototype); -``` - -- A: `{ constructor: ...}` `{ constructor: ...}` -- B: `{}` `{ constructor: ...}` -- C: `{ constructor: ...}` `{}` -- D: `{ constructor: ...}` `undefined` - -
Answer -

- -#### Answer: D - -Regular functions, such as the `giveLydiaPizza` function, have a `prototype` property, which is an object (prototype object) with a `constructor` property. Arrow functions however, such as the `giveLydiaChocolate` function, do not have this `prototype` property. `undefined` gets returned when trying to access the `prototype` property using `giveLydiaChocolate.prototype`. - -

-
- ---- - -###### 93. What's the output? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -for (const [x, y] of Object.entries(person)) { - console.log(x, y); -} -``` - -- A: `name` `Lydia` and `age` `21` -- B: `["name", "Lydia"]` and `["age", 21]` -- C: `["name", "age"]` and `undefined` -- D: `Error` - -
Answer -

- -#### Answer: A - -`Object.entries(person)` returns an array of nested arrays, containing the keys and objects: - -`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` - -Using the `for-of` loop, we can iterate over each element in the array, the subarrays in this case. We can destructure the subarrays instantly in the for-of loop, using `const [x, y]`. `x` is equal to the first element in the subarray, `y` is equal to the second element in the subarray. - -The first subarray is `[ "name", "Lydia" ]`, with `x` equal to `"name"`, and `y` equal to `"Lydia"`, which get logged. -The second subarray is `[ "age", 21 ]`, with `x` equal to `"age"`, and `y` equal to `21`, which get logged. - -

-
- ---- - -###### 94. What's the output? - -```javascript -function getItems(fruitList, ...args, favoriteFruit) { - return [...fruitList, ...args, favoriteFruit] -} - -getItems(["banana", "apple"], "pear", "orange") -``` - -- A: `["banana", "apple", "pear", "orange"]` -- B: `[["banana", "apple"], "pear", "orange"]` -- C: `["banana", "apple", ["pear"], "orange"]` -- D: `SyntaxError` - -
Answer -

- -#### Answer: D - -`...args` is a rest parameter. The rest parameter's value is an array containing all remaining arguments, **and can only be the last parameter**! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error. - -```javascript -function getItems(fruitList, favoriteFruit, ...args) { - return [...fruitList, ...args, favoriteFruit]; -} - -getItems(['banana', 'apple'], 'pear', 'orange'); -``` - -The above example works. This returns the array `[ 'banana', 'apple', 'orange', 'pear' ]` - -

-
- ---- - -###### 95. What's the output? - -```javascript -function nums(a, b) { - if (a > b) console.log('a is bigger'); - else console.log('b is bigger'); - return; - a + b; -} - -console.log(nums(4, 2)); -console.log(nums(1, 2)); -``` - -- A: `a is bigger`, `6` and `b is bigger`, `3` -- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` -- C: `undefined` and `undefined` -- D: `SyntaxError` - -
Answer -

- -#### Answer: B - -In JavaScript, we don't _have_ to write the semicolon (`;`) explicitly, however the JavaScript engine still adds them after statements. This is called **Automatic Semicolon Insertion**. A statement can for example be variables, or keywords like `throw`, `return`, `break`, etc. - -Here, we wrote a `return` statement, and another value `a + b` on a _new line_. However, since it's a new line, the engine doesn't know that it's actually the value that we wanted to return. Instead, it automatically added a semicolon after `return`. You could see this as: - -```javascript -return; -a + b; -``` - -This means that `a + b` is never reached, since a function stops running after the `return` keyword. If no value gets returned, like here, the function returns `undefined`. Note that there is no automatic insertion after `if/else` statements! - -

-
- ---- - -###### 96. What's the output? - -```javascript -class Person { - constructor() { - this.name = 'Lydia'; - } -} - -Person = class AnotherPerson { - constructor() { - this.name = 'Sarah'; - } -}; - -const member = new Person(); -console.log(member.name); -``` - -- A: `"Lydia"` -- B: `"Sarah"` -- C: `Error: cannot redeclare Person` -- D: `SyntaxError` - -
Answer -

- -#### Answer: B - -We can set classes equal to other classes/function constructors. In this case, we set `Person` equal to `AnotherPerson`. The name on this constructor is `Sarah`, so the name property on the new `Person` instance `member` is `"Sarah"`. - -

-
- ---- - -###### 97. What's the output? - -```javascript -const info = { - [Symbol('a')]: 'b', -}; - -console.log(info); -console.log(Object.keys(info)); -``` - -- A: `{Symbol('a'): 'b'}` and `["{Symbol('a')"]` -- B: `{}` and `[]` -- C: `{ a: "b" }` and `["a"]` -- D: `{Symbol('a'): 'b'}` and `[]` - -
Answer -

- -#### Answer: D - -A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, and an empty array is returned. When logging the entire object, all properties will be visible, even non-enumerable ones. - -This is one of the many qualities of a symbol: besides representing an entirely unique value (which prevents accidental name collision on objects, for example when working with 2 libraries that want to add properties to the same object), you can also "hide" properties on objects this way (although not entirely. You can still access symbols using the `Object.getOwnPropertySymbols()` method). - -

-
- ---- - -###### 98. What's the output? - -```javascript -const getList = ([x, ...y]) => [x, y] -const getUser = user => { name: user.name, age: user.age } - -const list = [1, 2, 3, 4] -const user = { name: "Lydia", age: 21 } - -console.log(getList(list)) -console.log(getUser(user)) -``` - -- A: `[1, [2, 3, 4]]` and `undefined` -- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` -- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` -- D: `Error` and `{ name: "Lydia", age: 21 }` - -
Answer -

- -#### Answer: A - -The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: - -`[x, ...y] = [1, 2, 3, 4]` - -With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. - -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: - -`const getUser = user => ({ name: user.name, age: user.age })` - -Since no value gets returned in this case, the function returns `undefined`. - -

-
- ---- - -###### 99. What's the output? - -```javascript -const name = 'Lydia'; - -console.log(name()); -``` - -- A: `SyntaxError` -- B: `ReferenceError` -- C: `TypeError` -- D: `undefined` - -
Answer -

- -#### Answer: C - -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. - -TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! - -SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. -ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access. - -

-
- ---- - -###### 100. What's the value of output? - -```javascript -// 🎉✨ This is my 100th question! ✨🎉 - -const output = `${[] && 'Im'}possible! -You should${'' && `n't`} see a therapist after so much JavaScript lol`; -``` - -- A: `possible! You should see a therapist after so much JavaScript lol` -- B: `Impossible! You should see a therapist after so much JavaScript lol` -- C: `possible! You shouldn't see a therapist after so much JavaScript lol` -- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` - -
Answer -

- -#### Answer: B - -`[]` is a truthy value. With the `&&` operator, the right-hand value will be returned if the left-hand value is a truthy value. In this case, the left-hand value `[]` is a truthy value, so `"Im'` gets returned. - -`""` is a falsy value. If the left-hand value is falsy, nothing gets returned. `n't` doesn't get returned. - -

-
- ---- - -###### 101. What's the value of output? - -```javascript -const one = false || {} || null; -const two = null || false || ''; -const three = [] || 0 || true; - -console.log(one, two, three); -``` - -- A: `false` `null` `[]` -- B: `null` `""` `true` -- C: `{}` `""` `[]` -- D: `null` `null` `true` - -
Answer -

- -#### Answer: C - -With the `||` operator, we can return the first truthy operand. If all values are falsy, the last operand gets returned. - -`(false || {} || null)`: the empty object `{}` is a truthy value. This is the first (and only) truthy value, which gets returned. `one` is equal to `{}`. - -`(null || false || "")`: all operands are falsy values. This means that the last operand, `""` gets returned. `two` is equal to `""`. - -`([] || 0 || "")`: the empty array`[]` is a truthy value. This is the first truthy value, which gets returned. `three` is equal to `[]`. - -

-
- ---- - -###### 102. What's the value of output? - -```javascript -const myPromise = () => Promise.resolve('I have resolved!'); - -function firstFunction() { - myPromise().then(res => console.log(res)); - console.log('second'); -} - -async function secondFunction() { - console.log(await myPromise()); - console.log('second'); -} - -firstFunction(); -secondFunction(); -``` - -- A: `I have resolved!`, `second` and `I have resolved!`, `second` -- B: `second`, `I have resolved!` and `second`, `I have resolved!` -- C: `I have resolved!`, `second` and `second`, `I have resolved!` -- D: `second`, `I have resolved!` and `I have resolved!`, `second` - -
Answer -

- -#### Answer: D - -With a promise, we basically say _I want to execute this function, but I'll put it aside for now while it's running since this might take a while. Only when a certain value is resolved (or rejected), and when the call stack is empty, I want to use this value._ - -We can get this value with both `.then` and the `await` keyword in an `async` function. Although we can get a promise's value with both `.then` and `await`, they work a bit differently. - -In the `firstFunction`, we (sort of) put the myPromise function aside while it was running, but continued running the other code, which is `console.log('second')` in this case. Then, the function resolved with the string `I have resolved`, which then got logged after it saw that the callstack was empty. - -With the await keyword in `secondFunction`, we literally pause the execution of an async function until the value has been resolved before moving to the next line. - -This means that it waited for the `myPromise` to resolve with the value `I have resolved`, and only once that happened, we moved to the next line: `second` got logged. - -

-
- ---- - -###### 103. What's the value of output? - -```javascript -const set = new Set(); - -set.add(1); -set.add('Lydia'); -set.add({ name: 'Lydia' }); - -for (let item of set) { - console.log(item + 2); -} -``` - -- A: `3`, `NaN`, `NaN` -- B: `3`, `7`, `NaN` -- C: `3`, `Lydia2`, `[object Object]2` -- D: `"12"`, `Lydia2`, `[object Object]2` - -
Answer -

- -#### Answer: C - -The `+` operator is not only used for adding numerical values, but we can also use it to concatenate strings. Whenever the JavaScript engine sees that one or more values are not a number, it coerces the number into a string. - -The first one is `1`, which is a numerical value. `1 + 2` returns the number 3. - -However, the second one is a string `"Lydia"`. `"Lydia"` is a string and `2` is a number: `2` gets coerced into a string. `"Lydia"` and `"2"` get concatenated, which results in the string `"Lydia2"`. - -`{ name: "Lydia" }` is an object. Neither a number nor an object is a string, so it stringifies both. Whenever we stringify a regular object, it becomes `"[object Object]"`. `"[object Object]"` concatenated with `"2"` becomes `"[object Object]2"`. - -

-
- ---- - -###### 104. What's its value? - -```javascript -Promise.resolve(5); -``` - -- A: `5` -- B: `Promise {: 5}` -- C: `Promise {: 5}` -- D: `Error` - -
Answer -

- -#### Answer: C - -We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value. If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. - -In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. - -

-
- ---- - -###### 105. What's its value? - -```javascript -function compareMembers(person1, person2 = person) { - if (person1 !== person2) { - console.log('Not the same!'); - } else { - console.log('They are the same!'); - } -} - -const person = { name: 'Lydia' }; - -compareMembers(person); -``` - -- A: `Not the same!` -- B: `They are the same!` -- C: `ReferenceError` -- D: `SyntaxError` - -
Answer -

- -#### Answer: B - -Objects are passed by reference. When we check objects for strict equality (`===`), we're comparing their references. - -We set the default value for `person2` equal to the `person` object, and passed the `person` object as the value for `person1`. - -This means that both values have a reference to the same spot in memory, thus they are equal. - -The code block in the `else` statement gets run, and `They are the same!` gets logged. - -

-
- ---- - -###### 106. What's its value? - -```javascript -const colorConfig = { - red: true, - blue: false, - green: true, - black: true, - yellow: false, -}; - -const colors = ['pink', 'red', 'blue']; - -console.log(colorConfig.colors[1]); -``` - -- A: `true` -- B: `false` -- C: `undefined` -- D: `TypeError` - -
Answer -

- -#### Answer: D - -In JavaScript, we have two ways to access properties on an object: bracket notation, or dot notation. In this example, we use dot notation (`colorConfig.colors`) instead of bracket notation (`colorConfig["colors"]`). - -With dot notation, JavaScript tries to find the property on the object with that exact name. In this example, JavaScript tries to find a property called `colors` on the `colorConfig` object. There is no property called `colors`, so this returns `undefined`. Then, we try to access the value of the first element by using `[1]`. We cannot do this on a value that's `undefined`, so it throws a `TypeError`: `Cannot read property '1' of undefined`. - -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. If we would've used `colorConfig[colors[1]]`, it would have returned the value of the `red` property on the `colorConfig` object. - -

-
- ---- - -###### 107. What's its value? - -```javascript -console.log('❤️' === '❤️'); -``` - -- A: `true` -- B: `false` - -
Answer -

- -#### Answer: A - -Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. - -

-
- ---- - -###### 108. Which of these methods modifies the original array? - -```javascript -const emojis = ['✨', '🥑', '😍']; - -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); -``` - -- A: `All of them` -- B: `map` `reduce` `slice` `splice` -- C: `map` `slice` `splice` -- D: `splice` - -
Answer -

- -#### Answer: D - -With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` and `'😍'`) and added the ✨ emoji instead. - -`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. - -

-
- ---- - -###### 109. What's the output? - -```javascript -const food = ['🍕', '🍫', '🥑', '🍔']; -const info = { favoriteFood: food[0] }; - -info.favoriteFood = '🍝'; - -console.log(food); -``` - -- A: `['🍕', '🍫', '🥑', '🍔']` -- B: `['🍝', '🍫', '🥑', '🍔']` -- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` -- D: `ReferenceError` - -
Answer -

- -#### Answer: A - -We set the value of the `favoriteFood` property on the `info` object equal to the string with the pizza emoji, `'🍕'`. A string is a primitive data type. In JavaScript, primitive data types act by reference - -In JavaScript, primitive data types (everything that's not an object) interact by _value_. In this case, we set the value of the `favoriteFood` property on the `info` object equal to the value of the first element in the `food` array, the string with the pizza emoji in this case (`'🍕'`). A string is a primitive data type, and interact by value (see my [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) if you're interested in learning more) - -Then, we change the value of the `favoriteFood` property on the `info` object. The `food` array hasn't changed, since the value of `favoriteFood` was merely a _copy_ of the value of the first element in the array, and doesn't have a reference to the same spot in memory as the element on `food[0]`. When we log food, it's still the original array, `['🍕', '🍫', '🥑', '🍔']`. - -

-
- ---- - -###### 110. What does this method do? - -```javascript -JSON.parse(); -``` - -- A: Parses JSON to a JavaScript value -- B: Parses a JavaScript object to JSON -- C: Parses any JavaScript value to JSON -- D: Parses JSON to a JavaScript object only - -
Answer -

- -#### Answer: A - -With the `JSON.parse()` method, we can parse JSON string to a JavaScript value. - -```javascript -// Stringifying a number into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonNumber = JSON.stringify(4); // '4' -JSON.parse(jsonNumber); // 4 - -// Stringifying an array value into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' -JSON.parse(jsonArray); // [1, 2, 3] - -// Stringifying an object into valid JSON, then parsing the JSON string to a JavaScript value: -const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' -JSON.parse(jsonArray); // { name: 'Lydia' } -``` - -

-
- ---- - -###### 111. What's the output? - -```javascript -let name = 'Lydia'; - -function getName() { - console.log(name); - let name = 'Sarah'; -} - -getName(); -``` - -- A: Lydia -- B: Sarah -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: D - -Each function has its own _execution context_ (or _scope_). The `getName` function first looks within its own context (scope) to see if it contains the variable `name` we're trying to access. In this case, the `getName` function contains its own `name` variable: we declare the variable `name` with the `let` keyword, and with the value of `'Sarah'`. - -Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. - -If we wouldn't have declared the `name` variable within the `getName` function, the javascript engine would've looked down the _scope chain_. The outer scope has a variable called `name` with the value of `Lydia`. In that case, it would've logged `Lydia`. - -```javascript -let name = 'Lydia'; - -function getName() { - console.log(name); -} - -getName(); // Lydia -``` - -

-
- ---- - -###### 112. What's the output? - -```javascript -function* generatorOne() { - yield ['a', 'b', 'c']; -} - -function* generatorTwo() { - yield* ['a', 'b', 'c']; -} - -const one = generatorOne(); -const two = generatorTwo(); - -console.log(one.next().value); -console.log(two.next().value); -``` - -- A: `a` and `a` -- B: `a` and `undefined` -- C: `['a', 'b', 'c']` and `a` -- D: `a` and `['a', 'b', 'c']` - -
Answer -

- -#### Answer: C - -With the `yield` keyword, we `yield` values in a generator function. With the `yield*` keyword, we can yield values from another generator function, or iterable object (for example an array). - -In `generatorOne`, we yield the entire array `['a', 'b', 'c']` using the `yield` keyword. The value of `value` property on the object returned by the `next` method on `one` (`one.next().value`) is equal to the entire array `['a', 'b', 'c']`. - -```javascript -console.log(one.next().value); // ['a', 'b', 'c'] -console.log(one.next().value); // undefined -``` - -In `generatorTwo`, we use the `yield*` keyword. This means that the first yielded value of `two`, is equal to the first yielded value in the iterator. The iterator is the array `['a', 'b', 'c']`. The first yielded value is `a`, so the first time we call `two.next().value`, `a` is returned. - -```javascript -console.log(two.next().value); // 'a' -console.log(two.next().value); // 'b' -console.log(two.next().value); // 'c' -console.log(two.next().value); // undefined -``` - -

-
- ---- - -###### 113. What's the output? - -```javascript -console.log(`${(x => x)('I love')} to program`); -``` - -- A: `I love to program` -- B: `undefined to program` -- C: `${(x => x)('I love') to program` -- D: `TypeError` - -
Answer -

- -#### Answer: A - -Expressions within template literals are evaluated first. This means that the string will contain the returned value of the expression, the immediately invoked function `(x => x)('I love')` in this case. We pass the value `'I love'` as an argument to the `x => x` arrow function. `x` is equal to `'I love'`, which gets returned. This results in `I love to program`. - -

-
- ---- - -###### 114. What will happen? - -```javascript -let config = { - alert: setInterval(() => { - console.log('Alert!'); - }, 1000), -}; - -config = null; -``` - -- A: The `setInterval` callback won't be invoked -- B: The `setInterval` callback gets invoked once -- C: The `setInterval` callback will still be called every second -- D: We never invoked `config.alert()`, config is `null` - -
Answer -

- -#### Answer: C - -Normally when we set objects equal to `null`, those objects get _garbage collected_ as there is no reference anymore to that object. However, since the callback function within `setInterval` is an arrow function (thus bound to the `config` object), the callback function still holds a reference to the `config` object. As long as there is a reference, the object won't get garbage collected. Since it's not garbage collected, the `setInterval` callback function will still get invoked every 1000ms (1s). - -

-
- ---- - -###### 115. Which method(s) will return the value `'Hello world!'`? - -```javascript -const myMap = new Map(); -const myFunc = () => 'greeting'; - -myMap.set(myFunc, 'Hello world!'); - -//1 -myMap.get('greeting'); -//2 -myMap.get(myFunc); -//3 -myMap.get(() => 'greeting'); -``` - -- A: 1 -- B: 2 -- C: 2 and 3 -- D: All of them - -
Answer -

- -#### Answer: B - -When adding a key/value pair using the `set` method, the key will be the value of the first argument passed to the `set` function, and the value will be the second argument passed to the `set` function. The key is the _function_ `() => 'greeting'` in this case, and the value `'Hello world'`. `myMap` is now `{ () => 'greeting' => 'Hello world!' }`. - -1 is wrong, since the key is not `'greeting'` but `() => 'greeting'`. -3 is wrong, since we're creating a new function by passing it as a parameter to the `get` method. Object interact by _reference_. Functions are objects, which is why two functions are never strictly equal, even if they are identical: they have a reference to a different spot in memory. - -

-
- ---- - -###### 116. What's the output? - -```javascript -const person = { - name: 'Lydia', - age: 21, -}; - -const changeAge = (x = { ...person }) => (x.age += 1); -const changeAgeAndName = (x = { ...person }) => { - x.age += 1; - x.name = 'Sarah'; -}; - -changeAge(person); -changeAgeAndName(); - -console.log(person); -``` - -- A: `{name: "Sarah", age: 22}` -- B: `{name: "Sarah", age: 23}` -- C: `{name: "Lydia", age: 22}` -- D: `{name: "Lydia", age: 23}` - -
Answer -

- -#### Answer: C - -Both the `changeAge` and `changeAgeAndName` functions have a default parameter, namely a _newly_ created object `{ ...person }`. This object has copies of all the key/values in the `person` object. - -First, we invoke the `changeAge` function and pass the `person` object as its argument. This function increases the value of the `age` property by 1. `person` is now `{ name: "Lydia", age: 22 }`. - -Then, we invoke the `changeAgeAndName` function, however we don't pass a parameter. Instead, the value of `x` is equal to a _new_ object: `{ ...person }`. Since it's a new object, it doesn't affect the values of the properties on the `person` object. `person` is still equal to `{ name: "Lydia", age: 22 }`. - -

-
- ---- - -###### 117. Which of the following options will return `6`? - -```javascript -function sumValues(x, y, z) { - return x + y + z; -} -``` - -- A: `sumValues([...1, 2, 3])` -- B: `sumValues([...[1, 2, 3]])` -- C: `sumValues(...[1, 2, 3])` -- D: `sumValues([1, 2, 3])` - -
Answer -

- -#### Answer: C - -With the spread operator `...`, we can _spread_ iterables to individual elements. The `sumValues` function receives three arguments: `x`, `y` and `z`. `...[1, 2, 3]` will result in `1, 2, 3`, which we pass to the `sumValues` function. - -

-
- ---- - -###### 118. What's the output? - -```javascript -let num = 1; -const list = ['🥳', '🤠', '🥰', '🤪']; - -console.log(list[(num += 1)]); -``` - -- A: `🤠` -- B: `🥰` -- C: `SyntaxError` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -With the `+=` operand, we're incrementing the value of `num` by `1`. `num` had the initial value `1`, so `1 + 1` is `2`. The item on the second index in the `list` array is 🥰, `console.log(list[2])` prints 🥰. - -

-
- ---- - -###### 119. What's the output? - -```javascript -const person = { - firstName: 'Lydia', - lastName: 'Hallie', - pet: { - name: 'Mara', - breed: 'Dutch Tulip Hound', - }, - getFullName() { - return `${this.firstName} ${this.lastName}`; - }, -}; - -console.log(person.pet?.name); -console.log(person.pet?.family?.name); -console.log(person.getFullName?.()); -console.log(member.getLastName?.()); -``` - -- A: `undefined` `undefined` `undefined` `undefined` -- B: `Mara` `undefined` `Lydia Hallie` `undefined` -- C: `Mara` `null` `Lydia Hallie` `null` -- D: `null` `ReferenceError` `null` `ReferenceError` - -
Answer -

- -#### Answer: B - -With the optional chaining operator `?.`, we no longer have to explicitly check whether the deeper nested values are valid or not. If we're trying to access a property on an `undefined` or `null` value (_nullish_), the expression short-circuits and returns `undefined`. - -`person.pet?.name`: `person` has a property named `pet`: `person.pet` is not nullish. It has a property called `name`, and returns `Mara`. -`person.pet?.family?.name`: `person` has a property named `pet`: `person.pet` is not nullish. `pet` does _not_ have a property called `family`, `person.pet.family` is nullish. The expression returns `undefined`. -`person.getFullName?.()`: `person` has a property named `getFullName`: `person.getFullName()` is not nullish and can get invoked, which returns `Lydia Hallie`. -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. - -

-
- ---- - -###### 120. What's the output? - -```javascript -const groceries = ['banana', 'apple', 'peanuts']; - -if (groceries.indexOf('banana')) { - console.log('We have to buy bananas!'); -} else { - console.log(`We don't have to buy bananas!`); -} -``` - -- A: We have to buy bananas! -- B: We don't have to buy bananas -- C: `undefined` -- D: `1` - -
Answer -

- -#### Answer: B - -We passed the condition `groceries.indexOf("banana")` to the if-statement. `groceries.indexOf("banana")` returns `0`, which is a falsy value. Since the condition in the if-statement is falsy, the code in the `else` block runs, and `We don't have to buy bananas!` gets logged. - -

-
- ---- - -###### 121. What's the output? - -```javascript -const config = { - languages: [], - set language(lang) { - return this.languages.push(lang); - }, -}; - -console.log(config.language); -``` - -- A: `function language(lang) { this.languages.push(lang }` -- B: `0` -- C: `[]` -- D: `undefined` - -
Answer -

- -#### Answer: D - -The `language` method is a `setter`. Setters don't hold an actual value, their purpose is to _modify_ properties. When calling a `setter` method, `undefined` gets returned. - -

-
- ---- - -###### 122. What's the output? - -```javascript -const name = 'Lydia Hallie'; - -console.log(!typeof name === 'object'); -console.log(!typeof name === 'string'); -``` - -- A: `false` `true` -- B: `true` `false` -- C: `false` `false` -- D: `true` `true` - -
Answer -

- -#### Answer: C - -`typeof name` returns `"string"`. The string `"string"` is a truthy value, so `!typeof name` returns the boolean value `false`. `false === "object"` and `false === "string"` both return`false`. - -(If we wanted to check whether the type was (un)equal to a certain type, we should've written `!==` instead of `!typeof`) - -

-
- ---- - -###### 123. What's the output? - -```javascript -const add = x => y => z => { - console.log(x, y, z); - return x + y + z; -}; - -add(4)(5)(6); -``` - -- A: `4` `5` `6` -- B: `6` `5` `4` -- C: `4` `function` `function` -- D: `undefined` `undefined` `6` - -
Answer -

- -#### Answer: A - -The `add` function returns an arrow function, which returns an arrow function, which returns an arrow function (still with me?). The first function receives an argument `x` with the value of `4`. We invoke the second function, which receives an argument `y` with the value `5`. Then we invoke the third function, which receives an argument `z` with the value `6`. When we're trying to access the value `x`, `y` and `z` within the last arrow function, the JS engine goes up the scope chain in order to find the values for `x` and `y` accordingly. This returns `4` `5` `6`. - -

-
- ---- - -###### 124. What's the output? - -```javascript -async function* range(start, end) { - for (let i = start; i <= end; i++) { - yield Promise.resolve(i); - } -} - -(async () => { - const gen = range(1, 3); - for await (const item of gen) { - console.log(item); - } -})(); -``` - -- A: `Promise {1}` `Promise {2}` `Promise {3}` -- B: `Promise {}` `Promise {}` `Promise {}` -- C: `1` `2` `3` -- D: `undefined` `undefined` `undefined` - -
Answer -

- -#### Answer: C - -The generator function `range` returns an async object with promises for each item in the range we pass: `Promise{1}`, `Promise{2}`, `Promise{3}`. We set the variable `gen` equal to the async object, after which we loop over it using a `for await ... of` loop. We set the variable `item` equal to the returned Promise values: first `Promise{1}`, then `Promise{2}`, then `Promise{3}`. Since we're _awaiting_ the value of `item`, the resolved promsie, the resolved _values_ of the promises get returned: `1`, `2`, then `3`. - -

-
- ---- - -###### 125. What's the output? - -```javascript -const myFunc = ({ x, y, z }) => { - console.log(x, y, z); -}; - -myFunc(1, 2, 3); -``` - -- A: `1` `2` `3` -- B: `{1: 1}` `{2: 2}` `{3: 3}` -- C: `{ 1: undefined }` `undefined` `undefined` -- D: `undefined` `undefined` `undefined` - -
Answer -

- -#### Answer: D - -`myFunc` expects an object with properties `x`, `y` and `z` as its argument. Since we're only passing three separate numeric values (1, 2, 3) instead of one object with properties `x`, `y` and `z` ({x: 1, y: 2, z: 3}), `x`, `y` and `z` have their default value of `undefined`. - -

-
- ---- - -###### 126. What's the output? - -```javascript -function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ - 'en-US', - { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) - - const formattedAmount = new Intl.NumberFormat({ - 'en-US', - { style: 'currency', currency: 'USD' } - }).format(amount) - - return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` -} - -console.log(getFine(130, 300)) -``` - -- A: The driver drove 130 and has to pay 300 -- B: The driver drove 130 mph and has to pay \$300.00 -- C: The driver drove undefined and has to pay undefined -- D: The driver drove 130.00 and has to pay 300.00 - -
Answer -

- -#### Answer: B - -With the `Intl.NumberFormat` method, we can format numeric values to any locale. We format the numeric value `130` to the `en-US` locale as a `unit` in `mile-per-hour`, which results in `130 mph`. The numeric value `300` to the `en-US` locale as a `currentcy` in `USD` results in `$300.00`. - -

-
- ---- - -###### 127. What's the output? - -```javascript -const spookyItems = ['👻', '🎃', '🕸']; -({ item: spookyItems[3] } = { item: '💀' }); - -console.log(spookyItems); -``` - -- A: `["👻", "🎃", "🕸"]` -- B: `["👻", "🎃", "🕸", "💀"]` -- C: `["👻", "🎃", "🕸", { item: "💀" }]` -- D: `["👻", "🎃", "🕸", "[object Object]"]` - -
Answer -

- -#### Answer: B - -By destructuring objects, we can unpack values from the right-hand object, and assign the unpacked value to the value of the same property name on the left-hand object. In this case, we're assigning the value "💀" to `spookyItems[3]`. This means that we're modifying the `spookyItems` array, we're adding the "💀" to it. When logging `spookyItems`, `["👻", "🎃", "🕸", "💀"]` gets logged. - -

-
- ---- - -###### 128. What's the output? - -```javascript -const name = 'Lydia Hallie'; -const age = 21; - -console.log(Number.isNaN(name)); -console.log(Number.isNaN(age)); - -console.log(isNaN(name)); -console.log(isNaN(age)); -``` - -- A: `true` `false` `true` `false` -- B: `true` `false` `false` `false` -- C: `false` `false` `true` `false` -- D: `false` `true` `false` `true` - -
Answer -

- -#### Answer: C - -With the `Number.isNaN` method, you can check if the value you pass is a _numeric value_ and equal to `NaN`. `name` is not a numeric value, so `Number.isNaN(name)` returns `false`. `age` is a numeric value, but is not equal to `NaN`, so `Number.isNaN(age)` returns `false`. - -With the `isNaN` method, you can check if the value you pass is not a number. `name` is not a number, so `isNaN(name)` returns true. `age` is a number, so `isNaN(age)` returns `false`. - -

-
- ---- - -###### 129. What's the output? - -```javascript -const randomValue = 21; - -function getInfo() { - console.log(typeof randomValue); - const randomValue = 'Lydia Hallie'; -} - -getInfo(); -``` - -- A: `"number"` -- B: `"string"` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: D - -Variables declared with the `const` keyword are not referencable before their initialization: this is called the _temporal dead zone_. In the `getInfo` function, the variable `randomValue` is scoped in the functional scope of `getInfo`. On the line where we want to log the value of `typeof randomValue`, the variable `randomValue` isn't initialized yet: a `ReferenceError` gets thrown! The engine didn't go down the scope chain since we declared the variable `randomValue` in the `getInfo` function. - -

-
- ---- - -###### 130. What's the output? - -```javascript -const myPromise = Promise.resolve('Woah some cool data'); - -(async () => { - try { - console.log(await myPromise); - } catch { - throw new Error(`Oops didn't work`); - } finally { - console.log('Oh finally!'); - } -})(); -``` - -- A: `Woah some cool data` -- B: `Oh finally!` -- C: `Woah some cool data` `Oh finally!` -- D: `Oops didn't work` `Oh finally!` - -
Answer -

- -#### Answer: C - -In the `try` block, we're logging the awaited value of the `myPromise` variable: `"Woah some cool data"`. Since no errors were thrown in the `try` block, the code in the `catch` block doesn't run. The code in the `finally` block _always_ runs, `"Oh finally!"` gets logged. - -

-
- ---- - -###### 131. What's the output? - -```javascript -const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; - -console.log(emojis.flat(1)); -``` - -- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` -- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` -- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` -- D: `['🥑', '✨', '✨', '🍕', '🍕']` - -
Answer -

- -#### Answer: B - -With the `flat` method, we can create a new, flattened array. The depth of the flattened array depends on the value that we pass. In this case, we passed the value `1` (which we didn't have to, that's the default value), meaning that only the arrays on the first depth will be concatenated. `['🥑']` and `['✨', '✨', ['🍕', '🍕']]` in this case. Concatenating these two arrays results in `['🥑', '✨', '✨', ['🍕', '🍕']]`. - -

-
- ---- - -###### 132. What's the output? - -```javascript -class Counter { - constructor() { - this.count = 0; - } - - increment() { - this.count++; - } -} - -const counterOne = new Counter(); -counterOne.increment(); -counterOne.increment(); - -const counterTwo = counterOne; -counterTwo.increment(); - -console.log(counterOne.count); -``` - -- A: `0` -- B: `1` -- C: `2` -- D: `3` - -
Answer -

- -#### Answer: D - -`counterOne` is an instance of the `Counter` class. The counter class contains a `count` property on its constructor, and an `increment` method. First, we invoked the `increment` method twice by calling `counterOne.increment()`. Currently, `counterOne.count` is `2`. - - - -Then, we create a new variable `counterTwo`, and set it equal to `counterOne`. Since objects interact by reference, we're just creating a new reference to the same spot in memory that `counterOne` points to. Since it has the same spot in memory, any changes made to the object that `counterTwo` has a reference to, also apply to `counterOne`. Currently, `counterTwo.count` is `2`. - -We invoke the `counterTwo.increment()`, which sets the `count` to `3`. Then, we log the count on `counterOne`, which logs `3`. - - - -

-
- ---- - -###### 133. What's the output? - -```javascript -const myPromise = Promise.resolve(Promise.resolve('Promise!')); - -function funcOne() { - myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); -} - -async function funcTwo() { - const res = await myPromise; - console.log(await res); - setTimeout(() => console.log('Timeout!', 0)); - console.log('Last line!'); -} - -funcOne(); -funcTwo(); -``` - -- A: `Promise! Last line! Promise! Last line! Last line! Promise!` -- B: `Last line! Timeout! Promise! Last line! Timeout! Promise!` -- C: `Promise! Last line! Last line! Promise! Timeout! Timeout!` -- D: `Last line! Promise! Promise! Last line! Timeout! Timeout!` - -
Answer -

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

-
- ---- - -###### 134. How can we invoke `sum` in `index.js` from `sum.js?` - -```javascript -// sum.js -export default function sum(x) { - return x + x; -} - -// index.js -import * as sum from './sum'; -``` - -- A: `sum(4)` -- B: `sum.sum(4)` -- C: `sum.default(4)` -- D: Default aren't imported with `*`, only named exports - -
Answer -

- -#### Answer: C - -With the asterisk `*`, we import all exported values from that file, both default and named. If we had the following file: - -```javascript -// info.js -export const name = 'Lydia'; -export const age = 21; -export default 'I love JavaScript'; - -// index.js -import * as info from './info'; -console.log(info); -``` - -The following would get logged: - -```javascript -{ - default: "I love JavaScript", - name: "Lydia", - age: 21 -} -``` - -For the `sum` example, it means that the imported value `sum` looks like this: - -```javascript -{ default: function sum(x) { return x + x } } -``` - -We can invoke this function, by calling `sum.default` - -

-
- ---- - -###### 135. What's the output? - -```javascript -const handler = { - set: () => console.log('Added a new property!'), - get: () => console.log('Accessed a property!'), -}; - -const person = new Proxy({}, handler); - -person.name = 'Lydia'; -person.name; -``` - -- A: `Added a new property!` -- B: `Accessed a property!` -- C: `Added a new property!` `Accessed a property!` -- D: Nothing gets logged - -
Answer -

- -#### Answer: C - -With a Proxy object, we can add custom behavior to an object that we pass to it as the second argument. In tis case, we pass the `handler` object which contained to properties: `set` and `get`. `set` gets invoked whenever we _set_ property values, `get` gets invoked whenever we _get_ (access) property values. - -The first argument is an empty object `{}`, which is the value of `person`. To this object, the custom behavior specified in the `handler` object gets added. If we add a property to the `person` object, `set` will get invoked. If we access a property on the `person` object, `get` gets invoked. - -First, we added a new property `name` to the proxy object (`person.name = "Lydia"`). `set` gets invoked, and logs `"Added a new property!"`. - -Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. - -

-
- ---- - -###### 136. Which of the following will modify the `person` object? - -```javascript -const person = { name: 'Lydia Hallie' }; - -Object.seal(person); -``` - -- A: `person.name = "Evan Bacon"` -- B: `person.age = 21` -- C: `delete person.name` -- D: `Object.assign(person, { age: 21 })` - -
Answer -

- -#### Answer: A - -With `Object.seal` we can prevent new properies from being _added_, or existing properties to be _removed_. - -However, you can still modify the value of existing properties. - -

-
- ---- - -###### 137. Which of the following will modify the `person` object? - -```javascript -const person = { - name: 'Lydia Hallie', - address: { - street: '100 Main St', - }, -}; - -Object.freeze(person); -``` - -- A: `person.name = "Evan Bacon"` -- B: `delete person.address` -- C: `person.address.street = "101 Main St"` -- D: `person.pet = { name: "Mara" }` - -
Answer -

- -#### Answer: C - -The `Object.freeze` method _freezes_ an object. No properties can be added, modified, or removed. - -However, it only _shallowly_ freezes the object, meaning that only _direct_ properties on the object are frozen. If the property is another object, like `address` in this case, the properties on that object aren't frozen, and can be modified. - -

-
- ---- - -###### 138. What's the output? - -```javascript -const add = x => x + x; - -function myFunc(num = 2, value = add(num)) { - console.log(num, value); -} - -myFunc(); -myFunc(3); -``` - -- A: `2` `4` and `3` `6` -- B: `2` `NaN` and `3` `NaN` -- C: `2` `Error` and `3` `6` -- D: `2` `4` and `3` `Error` - -
Answer -

- -#### Answer: A - -First, we invoked `myFunc()` without passing any arguments. Since we didn't pass arguments, `num` and `value` got their default values: num is `2`, and `value` the returned value of the function `add`. To the `add` function, we pass `num` as an argument, which had the value of `2`. `add` returns `4`, which is the value of `value`. - -Then, we invoked `myFunc(3)` and passed the value `3` as the value for the argument `num`. We didn't pass an argument for `value`. Since we didn't pass a value for the `value` argument, it got the default value: the returned value of the `add` function. To `add`, we pass `num`, which has the value of `3`. `add` returns `6`, which is the value of `value`. - -

-
- ---- - -###### 139. What's the output? - -```javascript -class Counter { - #number = 10 - - increment() { - this.#number++ - } - - getNum() { - return this.#number - } -} - -const counter = new Counter() -counter.increment() - -console.log(counter.#number) -``` - -- A: `10` -- B: `11` -- C: `undefined` -- D: `SyntaxError` - -
Answer -

- -#### Answer: D - -In ES2020, we can add private variables in classes by using the `#`. We cannot access these variables outside of the class. When we try to log `counter.#number`, a SyntaxError gets thrown: we cannot acccess it outside the `Counter` class! - -

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

- -#### Answer: B - -In order to iterate over the `members` in each element in the `teams` array, we need to pass `teams[i].members` to the `getMembers` generator function. The generator function returns a generator object. In order to iterate over each element in this generator object, we need to use `yield*`. - -If we would've written `yield`, `return yield`, or `return`, the entire generator function would've gotten returned the first time we called the `next` method. - -

-
- ---- - -###### 141. What's the output? - -```javascript -const person = { - name: 'Lydia Hallie', - hobbies: ['coding'], -}; - -function addHobby(hobby, hobbies = person.hobbies) { - hobbies.push(hobby); - return hobbies; -} - -addHobby('running', []); -addHobby('dancing'); -addHobby('baking', person.hobbies); - -console.log(person.hobbies); -``` - -- A: `["coding"]` -- B: `["coding", "dancing"]` -- C: `["coding", "dancing", "baking"]` -- D: `["coding", "running", "dancing", "baking"]` - -
Answer -

- -#### Answer: C - -The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. - -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `y`, `"running"` gets added to this empty array. - -Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. - -Last, we invoke the `addHobby` function, and pass `"bdaking"` as the value for `hobby`, and the `person.hobbies` array as the value for `hobbies`. We push the hobby `baking` to the `person.hobbies` array. - -After pushing `dancing` and `baking`, the value of `person.hobbies` is `["coding", "dancing", "baking"]` - -

-
- ---- - -###### 142. What's the output? - -```javascript -class Bird { - constructor() { - console.log("I'm a bird. 🦢"); - } -} - -class Flamingo extends Bird { - constructor() { - console.log("I'm pink. 🌸"); - super(); - } -} - -const pet = new Flamingo(); -``` - -- A: `I'm pink. 🌸` -- B: `I'm pink. 🌸` `I'm a bird. 🦢` -- C: `I'm a bird. 🦢` `I'm pink. 🌸` -- D: Nothing, we didn't call any method - -
Answer -

- -#### Answer: B - -We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. THe constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`. - -

-
- ---- - -###### 143. Which of the options result(s) in an error? - -```javascript -const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; - -/* 1 */ emojis.push('🦌'); -/* 2 */ emojis.splice(0, 2); -/* 3 */ emojis = [...emojis, '🥂']; -/* 4 */ emojis.length = 0; -``` - -- A: 1 -- B: 1 and 2 -- C: 3 and 4 -- D: 3 - -
Answer -

- -#### Answer: D - -The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. - -

-
- ---- - -###### 144. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? - -```javascript -const person = { - name: "Lydia Hallie", - age: 21 -} - -[...person] // ["Lydia Hallie", 21] -``` - -- A: Nothing, object are iterable by default -- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` -- C: `*[Symbol.iterator]() { yield* Object.values(this) }` -- D: `*[Symbol.iterator]() { for (let x in this) yield this }` - -
Answer -

- -#### Answer: C - -Objects aren't iterable by default. An iterable is an iterable if the iterator protocol is present. We can add this manually by adding the iterator symbol `[Symbol.iterator]`, which has to return a generator object, for example by making it a generator function `*[Symbol.iterator]() {}`. This generator function has to yield the `Object.values` of the `person` object if we want it to return the array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. - -

-
- ------ - -###### 146. What's the output? - -```javascript -let count = 0; -const nums = [0, 1, 2, 3]; - -nums.forEach(num => { - if (num) count += 1 -}) - -console.log(count) -``` - -- A: 1 -- B: 2 -- C: 3 -- D: 4 - -
Answer -

- -#### Answer: C - -The `if` condition within the `forEach` loop checks whether the value of `num` is truthy or falsy. Since the first number in the `nums` array is `0`, a falsy value, the `if` statement's code block won't be executed. `count` only gets incremented for the other 3 numbers in the `nums` array, `1`, `2` and `3`. Since `count` gets incremented by `1` 3 times, the value of `count` is `3`. - -

-
- ---- - -###### 147. What's the output? - -```javascript -function getFruit(fruits) { - console.log(fruits?.[1]?.[1]) -} - -getFruit([['🍊', '🍌'], ['🍍']]) -getFruit() -getFruit([['🍍'], ['🍊', '🍌']]) -``` - -- A: `null`, `undefined`, 🍌 -- B: `[]`, `null`, 🍌 -- C: `[]`, `[]`, 🍌 -- D: `undefined`, `undefined`, 🍌 - -
Answer -

- -#### Answer: D - -The `?` allows us to optionally access deeper nested properties within objects. We're trying to log the item on index `1` within the subarray that's on index `1` of the `fruits` array. If the subarray on index `1` in the `fruits` array doesn't exist, it'll simply return `undefined`. If the subarray on index `1` in the `fruits` array exists, but this subarray doesn't have an item on its `1` index, it'll also return `undefined`. - -First, we're trying to log the second item in the `['🍍']` subarray of `[['🍊', '🍌'], ['🍍']]]`. This subarray only contains one item, which means there is no item on index `1`, and returns `undefined`. - -Then, we're invoking the `getFruits` function without passing a value as an argument, which means that `fruits` has a value of `undefined` by default. Since we're conditionally chaining the item on index `1` of`fruits`, it returns `undefined` since this item on index `1` does not exist. - -Lastly, we're trying to log the second item in the `['🍊', '🍌']` subarray of `['🍍'], ['🍊', '🍌']`. The item on index `1` within this subarray is `🍌`, which gets logged. - -

-
- ---- - -###### 148. What's the output? - -```javascript -class Calc { - constructor() { - this.count = 0 - } - - increase() { - this.count ++ - } -} - -const calc = new Calc() -new Calc().increase() - -console.log(calc.count) -``` - -- A: `0` -- B: `1` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: A - -We set the variable `calc` equal to a new instance of the `Calc` class. Then, we instantiate a new instance of `Calc`, and invoke the `increase` method on this instance. Since the count property is within the constructor of the `Calc` class, the count property is not shared on the prototype of `Calc`. This means that the value of count has not been updated for the instance calc points to, count is still `0`. - -

-
- ---- - -###### 149. What's the output? - -```javascript -const user = { - email: "e@mail.com", - password: "12345" -} - -const updateUser = ({ email, password }) => { - if (email) { - Object.assign(user, { email }) - } - - if (password) { - user.password = password - } - - return user -} - -const updatedUser = updateUser({ email: "new@email.com" }) - -console.log(updatedUser === user) -``` - -- A: `false` -- B: `true` -- C: `TypeError` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -The `updateUser` function updates the values of the `email` and `password` properties on user, if their values are passed to the function, after which the function returns the `user` object. The returned value of the `updateUser` function is the `user` object, which means that the value of updatedUser is a reference to the same `user` object that `user` points to. `updatedUser === user` equals `true`. - -

-
- ---- - -###### 150. What's the output? - -```javascript -const fruit = ['🍌', '🍊', '🍎'] - -fruit.slice(0, 1) -fruit.splice(0, 1) -fruit.unshift('🍇') -``` - -- A: `['🍌', '🍊', '🍎']` -- B: `['🍊', '🍎']` -- C: `['🍇', '🍊', '🍎']` -- D: `['🍇', '🍌', '🍊', '🍎']` - -
Answer -

- -#### Answer: C - -First, we invoke the `slice` method on the fruit array. The slice method does not modify the original array, but returns the value that it sliced off the array: the banana emoji. -Then, we invoke the `splice` method on the fruit array. The splice method does modify the original array, which means that the fruit array now consists of `['🍊', '🍎']`. -At last, we invoke the `unshift` method on the `fruit` array, which modifies the original array by adding the provided value, ‘🍇’ in this case, as the first element in the array. The fruit array now consists of `['🍇', '🍊', '🍎']`. - -

-
- ---- - -######
151. What's the output? - -```javascript -const animals = {}; -let dog = { emoji: '🐶' } -let cat = { emoji: '🐈' } - -animals[dog] = { ...dog, name: "Mara" } -animals[cat] = { ...cat, name: "Sara" } - -console.log(animals[dog]) -``` - -- A: `{ emoji: "🐶", name: "Mara" }` -- B: `{ emoji: "🐈", name: "Sara" }` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: B - -Object keys are converted to strings. - -Since the value of `dog` is an object, `animals[dog]` actually means that we’re creating a new property called `"object Object"` equal to the new object. `animals["object Object"]` is now equal to `{ emoji: "🐶", name: "Mara"}`. - -`cat` is also an object, which means that `animals[cat]` actually means that we’re overwriting the value of `animals[``"``object Object``"``]` with the new cat properties. - -Logging `animals[dog]`, or actually `animals["object Object"]` since converting the `dog` object to a string results `"object Object"`, returns the `{ emoji: "🐈", name: "Sara" }`. - -

-
- ---- - -###### 152. What's the output? - -```javascript -const user = { - email: "my@email.com", - updateEmail: email => { - this.email = email - } -} - -user.updateEmail("new@email.com") -console.log(user.email) -``` - -- A: `my@email.com` -- B: `new@email.com` -- C: `undefined` -- D: `ReferenceError` - -
Answer -

- -#### Answer: A - -The `updateEmail` function is an arrow function, and is not bound to the `user` object. This means that the `this` keyword is not referring to the `user` object, but refers to the global scope in this case. The value of `email` within the `user` object does not get updated. When logging the value of `user.email`, the original value of `my@email.com` gets returned. - -

-
- ---- - -###### 153. What's the output? - -```javascript -const promise1 = Promise.resolve('First') -const promise2 = Promise.resolve('Second') -const promise3 = Promise.reject('Third') -const promise4 = Promise.resolve('Fourth') - -const runPromises = async () => { - const res1 = await Promise.all([promise1, promise2]) - const res2 = await Promise.all([promise3, promise4]) - return [res1, res2] -} - -runPromises() - .then(res => console.log(res)) - .catch(err => console.log(err)) -``` - -- A: `[['First', 'Second'], ['Fourth']]` -- B: `[['First', 'Second'], ['Third', 'Fourth']]` -- C: `[['First', 'Second']]` -- D: `'Third'` - -
Answer -

- -#### Answer: D - -The `Promise.all` method runs the passed promises in parallel. If one promise fails, the `Promise.all` method _rejects) with the value of the rejected promise. In this case, `promise3` rejected with the value `"Third"`. We’re catching the rejected value in the chained `catch` method on the `runPromises` invocation to catch any errors within the `runPromises` function. Only `"Third"` gets logged, since `promise3` rejected with this value. - -

-
\ No newline at end of file diff --git a/es-ES/README-ES.md b/es-ES/README-ES.md index a6247c9f..e839d901 100644 --- a/es-ES/README-ES.md +++ b/es-ES/README-ES.md @@ -12,23 +12,28 @@ Lista de lenguajes disponibles: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -374,11 +379,11 @@ console.log(member.getFullName()); #### Respuesta correcta: A -En JS no se pueden añadir propiedades a un constructor como se puede hacer con los objetos. Si se desea añadir una característica a todos los objetos a la vez, se debe utilizar el [prototipo](https://www.w3schools.com/js/js_object_prototypes.asp) en su lugar. Así que en este caso, +En JS no se pueden añadir propiedades a un constructor como se puede hacer con los objetos. Si se desea añadir una característica a todos los objetos a la vez, se debe utilizar [prototype](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes) en su lugar. Así que en este caso, ```js -Persona.prototipo.getFullName = función () {) - devuelve `${este.nombre} ${este.apellido}`; +Person.prototype.getFullName = function () {) + return `${this.firstName} ${this.lastName}`; } ``` @@ -833,7 +838,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1050,7 +1055,7 @@ typeof sayHi(); La función `sayHi` devuelve el valor devuelto de la función invocada inmediatamente ([IIFE](https://developer.mozilla.org/es/docs/Glossary/IIFE)). Esta función devuelve `0`, que es el tipo `"number"`. -En JS solo hay 7 tipos incorporados (En inglés se llaman _built-in types_, y pueden identificarse con el operador `typeof`. Más información [aquí](https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html)): `null`,` undefined`, `boolean`,` number`, `string`,` object` y `symbol`. `"function"` no es un tipo, ya que las funciones son objetos, es de tipo `"object"`. +En JS solo hay 7 tipos incorporados (En inglés se llaman _built-in types_, y pueden identificarse con el operador `typeof`. Más información [aquí](https://www.oreilly.com/library/view/you-dont-know/9781491905159/ch01.html)): `null`,` undefined`, `boolean`,` number`, `string`,` object`, `symbol` y `bigint`. `"function"` no es un tipo, ya que las funciones son objetos, es de tipo `"object"`.

@@ -3318,7 +3323,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Solución @@ -3326,7 +3331,7 @@ Promise.resolve(5) #### Answer: C -Podemos pasar cualquier tipo de valor que queramos a `Promise.resolve`, ya sea una promesa o no promesa. El método en sí mismo devuelve una promesa con el valor resuelto. Si pasas una función estandar, será una promesa resuelta con un valor normal. Si pasas una promesa, será una promesa resuelta con el valor resuelto de esa promesa pasada. +Podemos pasar cualquier tipo de valor que queramos a `Promise.resolve`, ya sea una promesa o no promesa. El método en sí mismo devuelve una promesa con el valor resuelto (``). Si pasas una función estandar, será una promesa resuelta con un valor normal. Si pasas una promesa, será una promesa resuelta con el valor resuelto de esa promesa pasada. En este caso, acabamos de pasar el valor numérico `5`. Devuelve una promesa resuelta con el valor `5`. diff --git a/fr-FR/README_fr-FR.md b/fr-FR/README_fr-FR.md index fc3a906a..16d0d14e 100644 --- a/fr-FR/README_fr-FR.md +++ b/fr-FR/README_fr-FR.md @@ -6,23 +6,28 @@ De la base aux subtilités du langage : testez votre compréhension de JavaScrip Les réponses se trouvent dans les sections repliées en dessous des questions, cliquez simplement dessus pour les faire apparaître. Bonne chance :heart: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -174,7 +179,7 @@ const mouse = { En JavaScript, toutes les clés d'objet sont des chaînes de caractères (sauf si c'est un Symbol). Bien que nous ne puissions pas les _typer_ comme des chaînes de caractères, elles sont converties en chaînes de caractères sous le capot. -JavaScript interprète (ou décompresse) les instructions. Lorsque nous utilisons la notation pas crochet, il voit le premier crochet `[` et continue jusqu'à ce qu'il trouve le crochet fermant `]`. Seulement après, il évalue l'instruction. +JavaScript interprète (ou décompresse) les instructions. Lorsque nous utilisons la notation par crochet, il voit le premier crochet `[` et continue jusqu'à ce qu'il trouve le crochet fermant `]`. Seulement après, il évalue l'instruction. `mouse[bird.size]` : Premièrement, il évalue `bird.size`, qui est `"small"`. `mouse["small"]` retourne `true`. @@ -685,7 +690,7 @@ sessionStorage.setItem("cool_secret", 123); #### Réponse : B -La donnée stocké dans le `sessionStorage` est supprimée après la fermeture de l'onglet. +La donnée stockée dans le `sessionStorage` est supprimée après la fermeture de l'onglet. Si vous utilisez le `localStorage`, la donnée sera là pour toujours, jusqu'à ce que, par exemple, `localStorage.clear()` soit invoquée. @@ -777,7 +782,7 @@ Si vous avez deux clés portant le même nom, la clé sera remplacée. Elle sera --- -###### 26. Le contexte global d'exécution de JavaScript crée 2 choses pour vous : l'objet global and le mot-clé `this`. +###### 26. Le contexte global d'exécution de JavaScript crée 2 choses pour vous : l'objet global et le mot-clé `this`. - A: Vrai - B: Faux @@ -830,7 +835,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1047,7 +1052,7 @@ typeof sayHi(); La fonction `sayHi` renvoie la valeur renvoyée par la fonction immédiatement appelée (IIFE). Cette fonction a renvoyé `0`, qui est du type `"nombre"`. -Pour info : il n'y a que 7 types natifs : `null`, `undefined`, `boolean`, `number`, `string`, `object` et `symbol`. `"function"` n'est pas un type, puisque les fonctions sont des objets, il est de type `"object"`. +Pour info : il n'y a que 7 types natifs : `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` et `bigint`. `"function"` n'est pas un type, puisque les fonctions sont des objets, il est de type `"object"`.

@@ -1068,7 +1073,7 @@ undefined; - A: `0`, `''`, `undefined` - B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` - C: `0`, `''`, `new Boolean(false)`, `undefined` -- D: All of them are falsy +- D: Toutes sont fausses
Réponse

@@ -1963,3 +1968,43 @@ L'opérateur arithmétique `++` _renvoie en premier_ la valeur de l'opérande, _

+ +--- + +###### 64. Quelle est la sortie? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Répondre +

+ +#### Répondre: C + +Dans ES6, nous pouvons initialiser les paramètres avec une valeur par défaut. La valeur du paramètre sera la valeur par défaut, si aucune autre valeur n'a été passée à la fonction, ou si la valeur du paramètre est `"undefined"`. Dans ce cas, nous répartissons les propriétés de l'objet `value` dans un nouvel objet, donc `x` a la valeur par défaut `{number: 10}`. + +L'argument par défaut est évalué at _call time_! Chaque fois que nous appelons la fonction, un a _new_ object créé. Nous invoquons la fonction `multiply` les deux premières fois sans passer de valeur: `x` a la valeur par défaut `{number: 10}`. Nous enregistrons ensuite la valeur multipliée de ce nombre, qui est `20`. + +La troisième fois que nous invoquons multiplier, nous passons un argument: l'objet appelé `value`. L'opérateur `* =` est en fait un raccourci pour `x.number = x.number * 2`: nous modifions la valeur de `x.number`, et enregistrons la valeur multipliée `20`. + +La quatrième fois, nous passons à nouveau l'objet `value`. `x.number` a été précédemment modifié en `20`, donc `x.number * = 2` enregistre «40». + +

+
+ +--- diff --git a/id-ID/README.md b/id-ID/README.md index a5c0becb..2f238d06 100644 --- a/id-ID/README.md +++ b/id-ID/README.md @@ -1,15 +1,11 @@ -
- -

Pertanyaan JavaScript

+

Pertanyaan JavaScript

---- + --- -Saya menerbitkan beberapa pilihan pertanyaan Javascript di akun Instagram Story [Instagram](https://www.instagram.com/theavocoder), yang mana diterbitkan disini juga! Terakhir diperbaharui: 24 Desember + Saya post pertanyaan pilihan ganda ke [Instagram](https://www.instagram.com/theavocoder) **stories** saya, yang saya post juga di sini ! update terakhir: December 24th -From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! :muscle: :rocket: I update this repo regularly with new questions. I added the answers in the **collapsed sections** below the questions, simply click on them to expand it. It's just for fun, good luck! :heart: -Dari tingkat dasar sampai tingkat lanjut: Menguji seberapa jago Anda di JavaScript, asah pengetahuan Anda, atau untuk persiapan interview tentang pemrograman! :muscle: :rocket: Saya akan memperbaharui jawaban di bagian yang tertutup di bawah pertanyaan, sederhananya tinggal di klik saja yang nantinya jawaban akan muncul disana. Ini hanya untuk bersenang - senang saja, semoga berhasil! :heart: + Mulai tingkat dasar ke mahir: tes seberapa paham kamu tentang javascript, segarkan sedikit pengetahuan kamu, atau bersiap-siap untuk coding interview kamu! :muscle: :rocket: Saya update repo ini secara berkala dengan pertanyaan baru. Saya masukkan jawaban dibagian yang **tersembunyi** di bawah pertanyaan, cukup klik pada bagian itu untuk menampilkannya. Pertanyaan ini hanya untuk bersenang-senang, Semoga berhasil :heart: -Feel free to reach out to me! 😊
Jangan sungkan untuk terhubung dengan saya! 😊
Instagram || Twitter || LinkedIn || Blog @@ -17,26 +13,31 @@ Jangan sungkan untuk terhubung dengan saya! 😊
--- -
Lihat 17 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹 +
Lihat 20 Terjemahan yang tersedia 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹🇽🇰

-- [English](../en-EN/README.md) -- [العربية](../ar-AR/README_AR.md) -- [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -- [Bosanski](../bs-BS/README-bs_BS.md) -- [Deutsch](../de-DE/README.md) -- [Español](../es-ES/README-ES.md) -- [Français](../fr-FR/README_fr-FR.md) -- [日本語](../ja-JA/README-ja_JA.md) -- [한국어](../ko-KR/README-ko_KR.md) -- [Português Brasil](../pt-BR/README_pt_BR.md) -- [Русский](../ru-RU/README.md) -- [Українська мова](../ua-UA/README-ua_UA.md) -- [Tiếng Việt](../vi-VI/README-vi.md) -- [中文版本](../zh-CN/README-zh_CN.md) -- [Türkçe](../tr-TR/README-tr_TR.md) -- [ไทย](../th-TH/README-th_TH.md) -- [Indonesia](../id-ID/README.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

@@ -56,20 +57,19 @@ function sayHi() { sayHi(); ``` -- A: `Lydia` and `undefined` -- B: `Lydia` and `ReferenceError` -- C: `ReferenceError` and `21` -- D: `undefined` and `ReferenceError` +- A: `Lydia` dan `undefined` +- B: `Lydia` dan `ReferenceError` +- C: `ReferenceError` dan `21` +- D: `undefined` dan `ReferenceError`
Jawaban

#### Jawaban: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. - -Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. +Di dalam function, kita membuat sebuah variabel `name` dan variabel tersebut di deklarasikan menggunakan `var`. Artinya variable tersebut di hoisting (dalam fase pembuatan ini menggunakan memory penyimpanan) dengan isi standar-nya `undefined`, saat javascript mengeksekusi baris code pembuatan variabel-nya. variabel `name` isinya masih undefined, jadi isi dari variabel tersebut `undefined` +Mendeklarasikan varibel menggunakan `let` (dan `const`) juga terkena hoisting, tidak seperti `var`, variabel declaration `let` dan `const` tidak ditentukan isi standar-nya. `let` dan `const` tidak bisa diakses sebelum di tentukan dulu isi-nya. Kejadian ini disebut "temporal dead zone". Saat kita mencoba memanggil variabel yang belum ditentukan isi-nya, Javascript mengeluarkan error `ReferenceError`.

@@ -96,10 +96,9 @@ for (let i = 0; i < 3; i++) { #### Jawaban: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. - -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +Karena antrean peristiwa di JavaScript, fungsi callback `setTimeout` disebut _after_ loop telah dijalankan. Karena variabel `i` di loop pertama dideklarasikan menggunakan kata kunci` var`, nilai ini adalah global. Selama perulangan, kita menambah nilai `i` sebesar `1` setiap kali, menggunakan operator unary` ++ `. Pada saat fungsi callback `setTimeout` dipanggil,` i` sama dengan `3` di contoh pertama. +Pada perulangan kedua, variabel `i` dideklarasikan menggunakan kata kunci` let`: variabel yang dideklarasikan dengan kata kunci `let` (dan` const`) memiliki cakupan blok (blok adalah apa saja di antara `{}`). Selama setiap iterasi, `i` akan memiliki nilai baru, dan setiap nilai dicakup di dalam loop.

@@ -120,21 +119,21 @@ console.log(shape.diameter()); console.log(shape.perimeter()); ``` -- A: `20` and `62.83185307179586` -- B: `20` and `NaN` -- C: `20` and `63` -- D: `NaN` and `63` +- A: `20` dan `62.83185307179586` +- B: `20` dan `NaN` +- C: `20` dan `63` +- D: `NaN` dan `63`
Jawaban

#### Jawaban: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Perhatikan pada nilai 'diameter' adalah fungsi biasa, sedangkan nilai 'perimeter' yaitu fungsi panah. -With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example). +Dengan fungsi panah, kata kunci 'this' merujuk ke cakupan sekitarnya saat ini, tidak seperti fungsi biasa. Ini berarti bahwa ketika kita memanggil 'perimeter' itu tidak mengacu pada objek bentuk, tetapi pada lingkup sekitarnya. -There is no value `radius` on that object, which returns `undefined`. +Tidak ada nilai 'radius' pada objek itu, yang mengembalikan 'tidak ditentukan'.

@@ -148,25 +147,26 @@ There is no value `radius` on that object, which returns `undefined`. !'Lydia'; ``` -- A: `1` and `false` -- B: `false` and `NaN` -- C: `false` and `false` +- A: `1` dan `false` +- B: `false` dan `NaN` +- C: `false` dan `false`
Jawaban

#### Jawaban: A -The unary plus tries to convert an operand to a number. `true` is `1`, and `false` is `0`. +Tia unary plus mencoba mengonversi operan menjadi angka. `true` adalah` 1`, dan `false` adalah` 0`. + +String "'Lydia'` adalah nilai yang benar. Apa yang sebenarnya kami tanyakan adalah "apakah nilai kebenaran ini salah?". Ini mengembalikan `salah`. -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`.

--- -###### 5. Which one is true? +###### 5. Mana yang benar? ```javascript const bird = { @@ -179,23 +179,20 @@ const mouse = { }; ``` -- A: `mouse.bird.size` is not valid -- B: `mouse[bird.size]` is not valid -- C: `mouse[bird["size"]]` is not valid -- D: All of them are valid +- A: `mouse.bird.size` tidak benar +- B: `mouse[bird.size]` tidak benar +- C: `mouse[bird["size"]]` tidak benar +- D: Semua jawaban benar
Jawaban

#### Jawaban: A +Pada JavaScript, semua kunci objek adalah string (kecuali jika itu berupa Simbol). Meskipun kita mungkin tidak mengetiknya sebagai string, tetap saja mereka selalu berubah menjadi string didalamnya. -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. - -JavaScript 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` +JavaScript menginterpretasikan (atau membuka) pernyataan-pernyataan. Saat kita menggunakan notasi kurung siku, ia melihat kurung buka pertama `[` dan terus berjalan sampai menemukan kurung tutup `]`. Baru setelah itu akan mengevaluasi pernyataannya. `mouse[bird.size]`: Pertama, ini mengevaluasi `bird.size`, yang mana `"small"`. `mouse["small"]` mengembalikan nilai `true`. -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +Namun, dengan notasi dot (.), hal ini tidak terjadi. `mouse` tidak memiliki kunci dengan nama `bird`, yang menyebabkan `mouse.bird` bernilai `undefined`. Kemudian, kita meminta `size` untuk menggunakan notasi dot (.): `mouse.bird.size`. Kita mengetahui bahwa `mouse.bird` bernilai `undefined`, yang sebenarnya kita minta adalah `undefined.size`. Yang mana hal ini tidak valid, dan akan memunculkan kesalahan yang mirip dengan `Cannot read property "size" of undefined`.

@@ -224,13 +221,13 @@ console.log(d.greeting); #### Jawaban: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +Dalam JavaScript, semua objek berinteraksi dengan _reference_ saat menyetelnya agar sama satu sama lain. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +Pertama, variabel `c` menyimpan nilai ke sebuah objek. Nanti, kita menetapkan `d` dengan referensi yang sama yang dimiliki` c` ke objek. -When you change one object, you change all of them. +Saat Anda mengubah satu objek, Anda mengubah semuanya.

@@ -259,11 +256,11 @@ console.log(b === c); #### Jawaban: C -`new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. +`new Number()` adalah konstruktor fungsi bawaan pada JavaScript. Meskipun hasilnya terlihat seperti integer, namun sebenarnya itu bukan integer: aslinya memiliki banyak fitur tambahan dan merupakan sebuah objek. -When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. +Saat kita menggunakan operator `==`, hal ini hanya akan memeriksa bahwa keduanya memiliki nilai yang sama. Pada kasus ini kedua variabel tersebut memiliki nilai yang sama, yaitu `3`, maka akan mengembalikan nilai `true`. -However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.` +Namun, saat kita menggunakan operator `===`, operator ini memeriksa bahwa kedua variabel memiliki nilai dan tipe yang sama. Bagaimanapun: `new Number()` bukanlah sebuah integer, ini adalah sebuah **object**. Keduanya akan mengembalikan nilai `false.`

@@ -298,7 +295,7 @@ console.log(freddie.colorChange('orange')); #### Jawaban: D -The `colorChange` function is static. Static methods are designed to live only on the constructor in which they are created, and cannot be passed down to any children. Since `freddie` is a child, the function is not passed down, and not available on the `freddie` instance: a `TypeError` is thrown. +Fungsi `colorChange` adalah statis. Metode statis dirancang hanya dapat aktif pada kontruktor dimana fungsi itu dibuat, dan tidak bisa dibawa ke-turunannya. Kita tahu bahwa `freddie` adalah sebuah turunan, maka fungsi itu tidak bisa turun, dan tidak tersedia pada instance `freddie`: sebuah pesan `TypeError` akan dikembalikan

@@ -322,16 +319,16 @@ console.log(greetign); #### Jawaban: A -It logs the object, because we just created an empty object on the global object! When we mistyped `greeting` as `greetign`, the JS interpreter actually saw this as `global.greetign = {}` (or `window.greetign = {}` in a browser). +Ini mencatat objek, karena kita baru saja membuat objek kosong di objek global! Saat kita salah mengetik `greeting` sebagai` greetign`, interpreter JS sebenarnya melihat ini sebagai `global.greetign = {}` (atau `window.greetign = {}` di browser). -In order to avoid this, we can use `"use strict"`. This makes sure that you have declared a variable before setting it equal to anything. +Untuk menghindari hal ini, kita bisa menggunakan `" use strict "`. Ini memastikan bahwa Anda telah mendeklarasikan variabel sebelum menetapkannya dengan apa pun.

--- -###### 10. What happens when we do this? +###### 10. Apa yang terjadi jika kita melakukan ini? ```javascript function bark() { @@ -351,9 +348,9 @@ bark.animal = 'dog'; #### Jawaban: A -This is possible in JavaScript, because functions are objects! (Everything besides primitive types are objects) +Ini dimungkinkan dalam JavaScript, karena fungsi adalah objek! (Segala sesuatu selain tipe primitif adalah objek) -A function is a special type of object. The code you write yourself isn't the actual function. The function is an object with properties. This property is invocable. +Fungsi adalah jenis objek khusus. Kode yang Anda tulis sendiri bukanlah fungsi sebenarnya. Fungsinya adalah objek dengan properti. Properti ini tidak dapat dipanggil.

@@ -386,7 +383,7 @@ console.log(member.getFullName()); #### Jawaban: A -You can't add properties to a constructor like you can with regular objects. If you want to add a feature to all objects at once, you have to use the prototype instead. So in this case, +Anda tidak dapat menambahkan properti ke constructor seperti yang Anda lakukan dengan objek biasa. Jika Anda ingin menambahkan fitur ke semua objek sekaligus, Anda harus menggunakan prototipe sebagai gantinya. Jadi dalam kasus ini: ```js Person.prototype.getFullName = function() { @@ -394,7 +391,7 @@ Person.prototype.getFullName = function() { }; ``` -would have made `member.getFullName()` work. Why is this beneficial? Say that we added this method to the constructor itself. Maybe not every `Person` instance needed this method. This would waste a lot of memory space, since they would still have that property, which takes of memory space for each instance. Instead, if we only add it to the prototype, we just have it at one spot in memory, yet they all have access to it! +Akan membuat `member.getFullName()` berfungsi. Mengapa ini bermanfaat? Katakanlah kita menambahkan metode ini ke konstruktor itu sendiri. Mungkin tidak setiap instance `Person` membutuhkan metode ini. Ini akan membuang banyak ruang memori, karena mereka masih memiliki properti itu, yang mengambil ruang memori untuk setiap instance. Sebaliknya, jika kita hanya menambahkannya ke prototipe, kita hanya memilikinya di satu tempat di memori, namun mereka semua memiliki akses ke sana!

@@ -416,26 +413,26 @@ console.log(lydia); console.log(sarah); ``` -- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` -- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` -- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` -- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` dan `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` dan `ReferenceError`
Jawaban

#### Jawaban: A -For `sarah`, we didn't use the `new` keyword. When using `new`, it refers to the new empty object we create. However, if you don't add `new` it refers to the **global object**! +Pada `sarah`, kita tidak menggunakan kata kunci `new`. Saat menggunakan `new`, Ini mengacu pada object kosong yang kita buat. Namun, jika Anda tidak menambahkan `new` ini merujuk pada **global object**! -We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smith"`. What we actually did, is defining `global.firstName = 'Sarah'` and `global.lastName = 'Smith'`. `sarah` itself is left `undefined`, since we don't return a value from the `Person` function. +Kita tahu bahwa `this.firstName` setara dengan `"Sarah"` dan `this.lastName` sama dengan `"Smith"`. Apa yang sebenarnya kami lakukan adalah mendefinisikan `global.firstName = 'Sarah'` dan `global.lastName = 'Smith'`. `sarah` sendiri dibiarkan `undefined`, karena kita tidak mengembalikan nilai dari fungsi `Person`.

--- -###### 13. What are the three phases of event propagation? +###### 13. Apa tiga fase dari event propagation? - A: Target > Capturing > Bubbling - B: Bubbling > Target > Capturing @@ -447,7 +444,7 @@ We said that `this.firstName` equals `"Sarah"` and `this.lastName` equals `"Smit #### Jawaban: D -During the **capturing** phase, the event goes through the ancestor elements down to the target element. It then reaches the **target** element, and **bubbling** begins. +Selama fase **capturing**, event melewati elemen ancestor hingga ke elemen target. Kemudian mencapai element **target**, dan **bubbling** dimulai. @@ -456,7 +453,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow --- -###### 14. All object have prototypes. +###### 14. Semua objek memiliki prototypes. - A: true - B: false @@ -466,7 +463,7 @@ During the **capturing** phase, the event goes through the ancestor elements dow #### Jawaban: B -All objects have prototypes, except for the **base object**. The base object is the object created by the user, or an object that is created using the `new` keyword. The base object has access to some methods and properties, such as `.toString`. This is the reason why you can use built-in JavaScript methods! All of such methods are available on the prototype. Although JavaScript can't find it directly on your object, it goes down the prototype chain and finds it there, which makes it accessible for you. +Semua objek memiliki prototypes, kecuali **objek dasar**. Objek dasar adalah objek yang dibuat oleh pengguna, atau objek yang dibuat dengan menggunakan kata kunci `baru`. Objek dasar memiliki akses ke beberapa metode dan properti, seperti `.toString`. Inilah alasan mengapa Anda dapat menggunakan metode JavaScript bawaan! Semua metode tersebut tersedia di prototipe. Meskipun JavaScript tidak dapat menemukannya secara langsung di objek Anda, JavaScript berada di rantai prototipe dan menemukannya di sana, yang membuatnya dapat diakses untuk Anda.

@@ -493,9 +490,9 @@ sum(1, '2'); #### Jawaban: C -JavaScript is a **dynamically typed language**: we don't specify what types certain variables are. Values can automatically be converted into another type without you knowing, which is called _implicit type coercion_. **Coercion** is converting from one type into another. +JavaScript adalah **Bahasa yang bersifat dinamis**: yang tidak menentukan jenis variabel tertentu. Values dapat secara otomatis diubah menjadi jenis lain tanpa Anda sadari, yang disebut _implicit type coercion_. **Coercion** adalah mengubah dari satu jenis ke jenis lainnya. -In this example, JavaScript converts the number `1` into a string, in order for the function to make sense and return a value. During the addition of a numeric type (`1`) and a string type (`'2'`), the number is treated as a string. We can concatenate strings like `"Hello" + "World"`, so what's happening here is `"1" + "2"` which returns `"12"`. +Pada contoh ini, JavaScript mengubah number `1` menjadi sebuah string, agar fungsi tersebut masuk akal dan mengembalikan nilai. Selama penambahan tipe numerik (`1`) dan tipe string (`'2'`), angka tersebut diperlakukan sebagai string. Kita bisa menggabungkan string seperti `"Hello" + "World"`, jadi yang terjadi di sini adalah `"1" + "2"` yang mengembalikan `"12"`.

@@ -521,17 +518,17 @@ console.log(number); #### Jawaban: C -The **postfix** unary operator `++`: +**Akhiran** operator unary `++`: -1. Returns the value (this returns `0`) -2. Increments the value (number is now `1`) +1. Mengembalikan nilai (ini mengembalikan `0`) +2. Menambahkan nilai (angkanya sekarang `1`) -The **prefix** unary operator `++`: +**Awalan** operator unary `++`: -1. Increments the value (number is now `2`) -2. Returns the value (this returns `2`) +1. Menambah nilai (angkanya sekarang `2`) +2. Mengembalikan nilai (ini mengembalikan `2`) -This returns `0 2 2`. +Ini mengembalikan `0 2 2`.

@@ -562,7 +559,7 @@ getPersonInfo`${person} is ${age} years old`; #### Jawaban: B -If you use tagged template literals, the value of the first argument is always an array of the string values. The remaining arguments get the values of the passed expressions! +Jika Anda menggunakan literal template yang diberi tag, nilai argumen pertama selalu berupa array bernilai string. Argumen yang tersisa mendapatkan nilai dari ekspresi yang diteruskan!

@@ -594,11 +591,11 @@ checkAge({ age: 18 }); #### Jawaban: C -When testing equality, primitives are compared by their _value_, while objects are compared by their _reference_. JavaScript checks if the objects have a reference to the same location in memory. +Saat menguji persamaan, primitif dibandingkan dengan nilainya, sedangkan objek dibandingkan dengan referensinya. JavaScript memeriksa apakah objek memiliki referensi ke lokasi yang sama di memori. -The two objects that we are comparing don't have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality. +Dua objek yang kita bandingkan tidak memiliki itu: objek yang kita lewati sebagai parameter merujuk ke lokasi yang berbeda dalam memori dari objek yang kita gunakan untuk memeriksa persamaan. -This is why both `{ age: 18 } === { age: 18 }` and `{ age: 18 } == { age: 18 }` return `false`. +Inilah mengapa `{age: 18} === {age: 18}` dan `{age: 18} == {age: 18}` mengembalikan nilai `false`.

@@ -625,7 +622,7 @@ getAge(21); #### Jawaban: C -The rest parameter (`...args`.) lets us "collect" all remaining arguments into an array. An array is an object, so `typeof args` returns `"object"` +Parameter sisanya (`... args`.) Memungkinkan kita "mengumpulkan" semua argumen yang tersisa ke dalam sebuah array. Array adalah sebuah objek, jadi `typeof args` mengembalikan "objek"

@@ -654,7 +651,7 @@ getAge(); #### Jawaban: C -With `"use strict"`, you can make sure that you don't accidentally declare global variables. We never declared the variable `age`, and since we use `"use strict"`, it will throw a reference error. If we didn't use `"use strict"`, it would have worked, since the property `age` would have gotten added to the global object. +Dengan `" use strict "`, Anda dapat memastikan bahwa Anda tidak mendeklarasikan variabel global secara tidak sengaja. Kita tidak pernah mendeklarasikan variabel `age`, dan karena kita menggunakan `" use strict "`, ini akan memunculkan kesalahan referensi. Jika kita tidak menggunakan `" use strict "`, ini akan berhasil, karena properti `age` akan ditambahkan ke objek global.

@@ -677,32 +674,32 @@ const sum = eval('10*10+5'); #### Jawaban: A -`eval` evaluates codes that's passed as a string. If it's an expression, like in this case, it evaluates the expression. The expression is `10 * 10 + 5`. This returns the number `105`. +`eval` mengevaluasi kode yang berlalu sebagai string. Jika itu adalah ekspresi, seperti dalam kasus ini, itu mengevaluasi ekspresi. Ungkapannya adalah `10 * 10 + 5`. Ini kembali nomor `105`.

--- -###### 22. How long is cool_secret accessible? +###### 22. Sampai berapa lama kah cool_secret dapat diakses? ```javascript sessionStorage.setItem('cool_secret', 123); ``` -- A: Forever, the data doesn't get lost. -- B: When the user closes the tab. -- C: When the user closes the entire browser, not only the tab. -- D: When the user shuts off their computer. +- A: Selamanya, data tersebut tidak akan hilang. +- B: Saat pengguna menutup tab browser. +- C: Saat pengguna menutup seluruh browser, tidak hanya tab. +- D: Saat pengguna mematikan komputernya.
Jawaban

#### Jawaban: B -The data stored in `sessionStorage` is removed after closing the _tab_. +Data yang disimpan di `sessionStorage` akan dihapus setelah menutup _tab_. -If you used `localStorage`, the data would've been there forever, unless for example `localStorage.clear()` is invoked. +Jika anda menggunakan `localStorage`, data tersebut akan tersimpan selamanya, kecuali misalnya _method_ `localStorage.clear()` dipanggil.

@@ -728,9 +725,9 @@ console.log(num); #### Jawaban: B -With the `var` keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. +Dengan kata kunci `var`, anda dapat menyatakan beberapa variabel dengan nama yang sama. Variabelnya akan memegang nilai terakhir. -You cannot do this with `let` or `const` since they're block-scoped. +Anda tidak dapat melakukan ini dengan `let` atau `const` karena mereka block-scoped.

@@ -785,7 +782,7 @@ console.log(obj); #### Jawaban: C -If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value. +Jika anda memiliki dua kunci dengan nama yang sama, kunci akan diganti. Ini masih dalam posisi pertama, tetapi dengan nilai terakhir yang ditentukan.

@@ -829,7 +826,7 @@ for (let i = 1; i < 5; i++) { #### Jawaban: C -The `continue` statement skips an iteration if a certain condition returns `true`. +Pernyataan `continue` melewatkan iterasi jika kondisi tertentu mengembalikan `true`.

@@ -845,7 +842,7 @@ String.prototype.giveLydiaPizza = () => { const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -858,7 +855,7 @@ name.giveLydiaPizza(); #### Jawaban: A -`String` is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method! +`String` adalah konstruksi dibangun, yang dapat kita tambahkan properti ke. Aku hanya menambahkan metode ke prototipe. String primitif string secara otomatis dikonversi menjadi objek string, dihasilkan oleh fungsi prototipe string. Jadi, semua string (objek string) memiliki akses ke metode itu!

@@ -921,31 +918,31 @@ baz(); #### Jawaban: B -We have a `setTimeout` function and invoked it first. Yet, it was logged last. +Kami memiliki fungsi `setTimeout` dan dimohonkan terlebih dahulu. Namun, itu login terakhir. -This is because in browsers, we don't just have the runtime engine, we also have something called a `WebAPI`. The `WebAPI` gives us the `setTimeout` function to start with, and for example the DOM. +Hal ini karena di browsers, kita tidak hanya memiliki mesin waktu runtime, kita juga memiliki sesuatu yang disebut `WebAPI`. `WebAPI` memberi kita fungsi `setTimeout`, dan misalnya DOM. -After the _callback_ is pushed to the WebAPI, the `setTimeout` function itself (but not the callback!) is popped off the stack. +Setelah _callback_ (panggilan balik) didorong ke WebAPI, fungsi `setTimeout` itu sendiri (tetapi tidak panggilan balik) muncul dari tumpukan. -Now, `foo` gets invoked, and `"First"` is being logged. +Sekarang, `foo` mendapat hambatan, dan `"First"` yang login. -`foo` is popped off the stack, and `baz` gets invoked. `"Third"` gets logged. +`foo` yang muncul dari tumpukan, dan `baz` mendapat perantara. `"Third"` akan login. -The WebAPI can't just add stuff to the stack whenever it's ready. Instead, it pushes the callback function to something called the _queue_. +WebAPI tidak bisa hanya menambahkan barang-barang ke tumpukan setiap kali siap. Sebaliknya, ia mendorong fungsi panggilan balik ke sesuatu yang disebut _queue_ (antrian). -This is where an event loop starts to work. An **event loop** looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack. +Di sinilah serangkaian acara mulai bekerja. Sebuah **event loop** (putaran kejadian/peristiwa) melihat tumpukan dan antrian tugas. Jika tumpukan kosong, itu mengambil hal pertama pada antrian dan mendorong ke tumpukan. -`bar` gets invoked, `"Second"` gets logged, and it's popped off the stack. +`bar` bisa dipanggil, `"Second"` akan login, dan itu muncul dari tumpukan.

@@ -1062,7 +1059,7 @@ console.log(typeof sayHi()); The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. -FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, and `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

@@ -1090,16 +1087,16 @@ undefined; #### Jawaban: A -There are only six falsy values: +Hanya ada enam nilai yang salah: - `undefined` - `null` - `NaN` - `0` -- `''` (empty string) +- `''` (string kosong) - `false` -Function constructors, like `new Number` and `new Boolean` are truthy. +Konstruktor fungsi, seperti Number baru dan Boolean baru, benar.

@@ -1148,11 +1145,11 @@ console.log(numbers); #### Jawaban: C -When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called "empty slots". These actually have the value of `undefined`, but you will see something like: +Saat Anda menyetel nilai ke elemen dalam larik yang melebihi panjang larik, JavaScript membuat sesuatu yang disebut "slot kosong". Ini sebenarnya memiliki nilai `tidak terdefinisi`, tetapi Anda akan melihat sesuatu seperti: `[1, 2, 3, 7 x empty, 11]` -depending on where you run it (it's different for every browser, node, etc.) +tergantung di mana Anda menjalankannya (berbeda untuk setiap browser, node, dll.)

@@ -1294,7 +1291,7 @@ setInterval(() => console.log('Hi'), 1000); #### Jawaban: A -It returns a unique id. This id can be used to clear that interval with the `clearInterval()` function. +Itu adalah mengembalikan sebuah id unik. id unik dapat digunakan untuk menghapus interval dengan menggunakan fungsi clearInterval()

@@ -1317,7 +1314,7 @@ It returns a unique id. This id can be used to clear that interval with the `cle #### Jawaban: A -A string is an iterable. The spread operator maps every character of an iterable to one element. +Sebuah string adalah iterable. Operator memetakan setiap karakter dari sebuah iterable ke dalam satu elemen.

@@ -1341,7 +1338,7 @@ console.log(gen.next().value); - A: `[0, 10], [10, 20]` - B: `20, 20` - C: `10, 20` -- D: `0, 10 and 10, 20` +- D: `0, 10 dan 10, 20`
Jawaban

@@ -1777,9 +1774,10 @@ console.log(myCounter); #### Jawaban: C -An imported module is _read-only_: you cannot modify the imported module. Only the module that exports them can change its value. +Modul yang diimpor adalah _read-only_: Anda tidak dapat mengubah modul yang diimpor. Hanya modul yang mengekspornya yang dapat mengubah nilainya. + +Ketika kita mencoba untuk menambah nilai `myCounter`, itu melemparkan kesalahan: `myCounter` adalah baca-saja dan tidak dapat dimodifikasi. -When we try to increment the value of `myCounter`, it throws an error: `myCounter` is read-only and cannot be modified.

@@ -2049,7 +2047,6 @@ On the fourth call, we again don't return from the callback function. The accumu

- --- ###### 66. With which constructor can we successfully extend the `Dog` class? @@ -2229,10 +2226,10 @@ console.log(/* 1 */); // Do you love JavaScript? console.log(/* 2 */); // JavaScript loves you back ❤️ ``` -- A: `game.next("Yes").value` and `game.next().value` -- B: `game.next.value("Yes")` and `game.next.value()` -- C: `game.next().value` and `game.next("Yes").value` -- D: `game.next.value()` and `game.next.value("Yes")` +- A: `game.next("Yes").value` dan `game.next().value` +- B: `game.next.value("Yes")` dan `game.next.value()` +- C: `game.next().value` dan `game.next("Yes").value` +- D: `game.next.value()` dan `game.next.value("Yes")`
Jawaban

@@ -2521,7 +2518,7 @@ With a _for-of_ loop, we can iterate over **iterables**. An array is an iterable --- -###### 80. What is the output? +###### 80. Apa yang akan tampil? ```javascript const list = [1 + 2, 1 * 2, 1 / 2]; @@ -2538,16 +2535,16 @@ console.log(list); #### Jawaban: C -Array elements can hold any value. Numbers, strings, objects, other arrays, null, boolean values, undefined, and other expressions such as dates, functions, and calculations. +Elemen array dapat berisi beberapa nilai. angka, string, objek, array lain, null, nilai boolean, undefined, dan lainnya seperti tanggal, fungsi, dan kalkulasi. -The element will be equal to the returned value. `1 + 2` returns `3`, `1 * 2` returns `2`, and `1 / 2` returns `0.5`. +elemen akan sama dengan nilai hasilnya. `1 + 2` menghasilkan `3`, `1 * 2` menghasilkan `2`, dan `1 / 2` menghasilkan `0.5`.

--- -###### 81. What is the output? +###### 81. Apa yang akan tampil? ```javascript function sayHi(name) { @@ -2567,13 +2564,13 @@ console.log(sayHi()); #### Jawaban: B -By default, arguments have the value of `undefined`, unless a value has been passed to the function. In this case, we didn't pass a value for the `name` argument. `name` is equal to `undefined` which gets logged. +Secara default, arguments memiliki nilai `undefined`, kecuali nilai telah diisi ke fungsi. Pada kasus ini, kita tidak mengisi nilai untuk argument `name`. `name` sama dengan `undefined` yang mana mendapat catatan. -In ES6, we can overwrite this default `undefined` value with default parameters. For example: +Di ES6, kita dapat menulis ulang nilai default `undefined` dengan parameter default. Sebagai contoh: `function sayHi(name = "Lydia") { ... }` -In this case, if we didn't pass a value or if we passed `undefined`, `name` would always be equal to the string `Lydia` +Pada kasus ini, juka kita tidak mengisi nilai atau mengisi `undefined`, `name` akan selalu sama dengan string `Lydia`

@@ -2693,8 +2690,8 @@ Variables with the `const` and `let` keyword are _block-scoped_. A block is anyt ```javascript fetch('https://www.website.com/api/user/1') - .then(res => res.json()) - .then(res => console.log(res)); + .then(res => res.json()) + .then(res => console.log(res)) ``` - A: The result of the `fetch` method. @@ -3070,7 +3067,7 @@ console.log(member.name); #### Jawaban: B -We can set classes equal to other classes/function constructors. In this case, we set `Person` equal to `AnotherPerson`. The name on this constructor is `Sarah`, so the name property on the new `Person` instance `member` is `"Sarah"`. +Kita dapat mengatur kelas yang sama dengan kelas / fungsi konstruktor lainnya. Dalam kasus ini, kita mengatur `Person` sama dengan `AnotherPerson`. Nama pada konstruktor ini adalah `Sarah`, jadi nama properti yang baru pada `Person` instance `member` adalah `"Sarah"`.

@@ -3098,9 +3095,9 @@ console.log(Object.keys(info)); #### Jawaban: D -A Symbol is not _enumerable_. The Object.keys method returns all _enumerable_ key properties on an object. The Symbol won't be visible, and an empty array is returned. When logging the entire object, all properties will be visible, even non-enumerable ones. +Simbol bukanlah merupakan suatu _enumerable_. Metode Object.keys akan mengembalikan semua properti kunci _enumerable_ pada sebuah objek. Simbol tidak akan terlihat, dan array kosong dikembalikan. Saat mencatat seluruh objek, semua properti akan terlihat, bahkan yang bukan non-enumerable. -This is one of the many qualities of a symbol: besides representing an entirely unique value (which prevents accidental name collision on objects, for example when working with 2 libraries that want to add properties to the same object), you can also "hide" properties on objects this way (although not entirely. You can still access symbols using the `Object.getOwnPropertySymbols()` method). +Ini adalah salah satu dari banyak kualitas simbol: Disamping selain mewakili nilai yang sepenuhnya unik (yang mencegah terjadinya benturan nama yang tidak disengaja pada objek, misalnya saat bekerja dengan 2 library yang ingin menambahkan properti ke objek yang sama), anda juga dapat "menyembunyikan" properti pada objek dengan cara ini (meskipun tidak seluruhnya. Anda masih dapat mengakses simbol menggunakan metode `Object.getOwnPropertySymbols()`).

@@ -3130,17 +3127,17 @@ console.log(getUser(user)) #### Jawaban: A -The `getList` function receives an array as its argument. Between the parentheses of the `getList` function, we destructure this array right away. You could see this as: +Fungsi `getList` menerima array sebagai argumennya. Di antara tanda kurung pada fungsi `getList`, Kita akan menstruktur ulang. Anda dapat melihat ini sebagai: `[x, ...y] = [1, 2, 3, 4]` -With the rest parameter `...y`, we put all "remaining" arguments in an array. The remaining arguments are `2`, `3` and `4` in this case. The value of `y` is an array, containing all the rest parameters. The value of `x` is equal to `1` in this case, so when we log `[x, y]`, `[1, [2, 3, 4]]` gets logged. +Dengan parameter sisa `...y`, kita akan meletakkan semua argumen "yang tersisa" dalam array. Dalam kasus ini argumen yang tersisa adalah `2`, `3` dan `4`. Nilai dari `y` merupakan suatu array, yang berisi semua parameter lainnya. Pada kasus ini nilai dari `x` sama dengan `1`, jadi saat kita mencatat `[x, y]`, maka catatannya `[1, [2, 3, 4]]`. -The `getUser` function receives an object. With arrow functions, we don't _have_ to write curly brackets if we just return one value. However, if you want to return an _object_ from an arrow function, you have to write it between parentheses, otherwise no value gets returned! The following function would have returned an object: +Fungsi `getUser` menerima sebuah objek. Dengan fungsi tanda panah, kita tidak _perlu_ menulis tanda kurung kurawal jika hanya mengembalikan satu nilai. Namun, jika anda mengembalikan nilai _object_ dari fungsi tanda panah, Anda harus menuliskannya di antara tanda kurung, jika tidak maka tidak ada nilai yang dikembalikan! Fungsi berikut akan mengembalikan sebuah objek: `const getUser = user => ({ name: user.name, age: user.age })` -Since no value gets returned in this case, the function returns `undefined`. +Karena tidak ada nilai yang dikembalikan dalam kasus ini, maka fungsi akan mengembalikan `undefined`.

@@ -3165,12 +3162,12 @@ console.log(name()); #### Jawaban: C -The variable `name` holds the value of a string, which is not a function, thus cannot invoke. +Variabel `name` menyimpan nilai string, yang bukan merupakan suatu fungsi, sehingga tidak dapat dipanggil. -TypeErrors get thrown when a value is not of the expected type. JavaScript expected `name` to be a function since we're trying to invoke it. It was a string however, so a TypeError gets thrown: name is not a function! +TypeErrors dilemparkan ketika nilai yang didapatkan bukan dari jenis yang kita harapkan. JavaScript mengharapkan `name` menjadi sebuah fungsi karena kita mencoba untuk memanggilnya. Namun itu adalah sebuah string, sehingga akan muncul TypeError gets thrown: name is not a function! -SyntaxErrors get thrown when you've written something that isn't valid JavaScript, for example when you've written the word `return` as `retrun`. -ReferenceErrors get thrown when JavaScript isn't able to find a reference to a value that you're trying to access. +SyntaxErrors muncul ketika anda salah menulis suatu Javascript, seperti `return` menjadi `retrun`. +ReferenceErrors muncul ketika JavaScript tidak dapat menemukan nilai referensi ke nilai yang anda coba akses.

@@ -3327,7 +3324,7 @@ Promise.resolve(5); - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Jawaban @@ -3335,7 +3332,7 @@ Promise.resolve(5); #### Jawaban: C -We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value. If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. +We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. @@ -3420,7 +3417,7 @@ JavaScript interprets (or unboxes) statements. When we use bracket notation, it --- -###### 107. What's its value? +###### 107. Apakah hasil nilai dibawah ini ? ```javascript console.log('❤️' === '❤️'); @@ -3434,24 +3431,24 @@ console.log('❤️' === '❤️'); #### Jawaban: A -Under the hood, emojis are unicodes. The unicodes for the heart emoji is `"U+2764 U+FE0F"`. These are always the same for the same emojis, so we're comparing two equal strings to each other, which returns true. +Di belakang layar, emoji adalah sebuah unicode. Unicode untuk emoji hati adalah `"U+2764 U+FE0F"`. Keduanya akan selalu sama untuk emoji yang sama, jadi sebetulnya kita telah membandingkan dua string yang sama satu sama lain, yang mana akan menghasilkan true.

--- -###### 108. Which of these methods modifies the original array? +###### 108. Manakah metode berikut yang akan memodifikasi array aslinya? ```javascript -const emojis = ['✨', '🥑', '😍']; +const emojis = ["✨", "🥑", "😍"]; -emojis.map(x => x + '✨'); -emojis.filter(x => x !== '🥑'); -emojis.find(x => x !== '🥑'); -emojis.reduce((acc, cur) => acc + '✨'); -emojis.slice(1, 2, '✨'); -emojis.splice(1, 2, '✨'); +emojis.map((x) => x + "✨"); +emojis.filter((x) => x !== "🥑"); +emojis.find((x) => x !== "🥑"); +emojis.reduce((acc, cur) => acc + "✨"); +emojis.slice(1, 2, "✨"); +emojis.splice(1, 2, "✨"); ``` - A: `All of them` @@ -3464,9 +3461,9 @@ emojis.splice(1, 2, '✨'); #### Jawaban: D -With `splice` method, we modify the original array by deleting, replacing or adding elements. In this case, we removed 2 items from index 1 (we removed `'🥑'` and `'😍'`) and added the ✨ emoji instead. +Metode `splice`, akan memodifikasi array aslinya dengan cara menghapus, mengganti atau menambahkan elemen. Dalam kasus ini, kami menghapus 2 item dari indeks 1 (kami menghapus `'🥑'` dan`' 😍'`) dan menambahkan emoji ✨ sebagai penggantinya. -`map`, `filter` and `slice` return a new array, `find` returns an element, and `reduce` returns a reduced value. +`map`,` filter` dan `slice` akan mengembalikan array baru,` find` akan mengembalikan elemen yang dicari, dan `reduce` akan mengembalikan nilai yang telah dikurangi.

@@ -4513,10 +4510,10 @@ myFunc(); myFunc(3); ``` -- A: `2` `4` and `3` `6` -- B: `2` `NaN` and `3` `NaN` -- C: `2` `Error` and `3` `6` -- D: `2` `4` and `3` `Error` +- A: `2` `4` dan `3` `6` +- B: `2` `NaN` dan `3` `NaN` +- C: `2` `Error` dan `3` `6` +- D: `2` `4` dan `3` `Error`
Jawaban

@@ -4605,9 +4602,9 @@ obj.next(); // { value: "Lisa", done: false } #### Jawaban: B -In order to iterate over the `members` in each element in the `teams` array, we need to pass `teams[i].members` to the `getMembers` generator function. The generator function returns a generator object. In order to iterate over each element in this generator object, we need to use `yield*`. +Untuk melakukan pengulangan pada `members` dalam setiap elemen array `tim`, kita perlu melemparkan `tim[i].members` ke fungsi generator `getMembers`. Fungsi generator akan mengembalikan objek hasil generator. Untuk mengulang setiap elemen dalam objek generator ini, kita perlu menggunakan `yield*`. -If we would've written `yield`, `return yield`, or `return`, the entire generator function would've gotten returned the first time we called the `next` method. +Jika kita telah menulis `yield`, `return yield`, atau `return`, maka seluruh fungsi generator akan dikembalikan saat pertama kali kita memanggil metode `next`.

@@ -4646,7 +4643,7 @@ console.log(person.hobbies); The `addHobby` function receives two arguments, `hobby` and `hobbies` with the default value of the `hobbies` array on the `person` object. -First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `y`, `"running"` gets added to this empty array. +First, we invoke the `addHobby` function, and pass `"running"` as the value for `hobby` and an empty array as the value for `hobbies`. Since we pass an empty array as the value for `hobbies`, `"running"` gets added to this empty array. Then, we invoke the `addHobby` function, and pass `"dancing"` as the value for `hobby`. We didn't pass a value for `hobbies`, so it gets the default value, the `hobbies` property on the `person` object. We push the hobby `dancing` to the `person.hobbies` array. @@ -4688,14 +4685,14 @@ const pet = new Flamingo(); #### Jawaban: B -We create the variable `pet` which is an instance of the `Flamingo` class. When we instantiate this instance, the `constructor` on `Flamingo` gets called. First, `"I'm pink. 🌸"` gets logged, after which we call `super()`. `super()` calls the constructor of the parent class, `Bird`. THe constructor in `Bird` gets called, and logs `"I'm a bird. 🦢"`. +Kita membuat variabel `pet` yang merupakan turunan dari class `Flamingo`. Saat kita membuat turunan, `constructor` pada `Flamingo` dipanggil. Pertama, `"I'm pink. 🌸"` ditampilkan, setelah itu kita memanggil `super()`. `super()` memanggil konstruktor class induk, `Bird`. Constructor pada `Bird` dipanggil, dan menampilkan `"I'm a bird. 🦢"`.

--- -###### 144. Which of the options result(s) in an error? +###### 144. Manakah dari pilihan di bawah ini yang salah? ```javascript const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; @@ -4707,8 +4704,8 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; ``` - A: 1 -- B: 1 and 2 -- C: 3 and 4 +- B: 1 dan 2 +- C: 3 dan 4 - D: 3
Jawaban @@ -4716,14 +4713,14 @@ const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; #### Jawaban: D -The `const` keyword simply means we cannot _redeclare_ the value of that variable, it's _read-only_. However, the value itself isn't immutable. The propeties on the `emojis` array can be modified, for example by pushing new values, splicing them, or setting the length of the array to 0. +Deklarasi `const` pada dasarnya berarti tidak dapat _mengubah_ nilai dari variable tersebut, karena bersifat _read-only (tidak dapat diubah)_. Bagaimanapun, nilainya tidak mutlak. Seperti array pada variable `emojis` dimana nilainya bisa diubah, contohnya untuk menambah nilai array baru, menghilangkan, atau mengubah properti `length` dari array menjadi 0.

--- -###### 145. What do we need to add to the `person` object to get `["Lydia Hallie", 21]` as the output of `[...person]`? +###### 145. Apa yang harus kita tambahkan ke objek `person` untuk mendapatkan `["Lydia Hallie", 21]` sebagai output dari `[...person]`? ```javascript const person = { @@ -4734,7 +4731,7 @@ const person = { [...person] // ["Lydia Hallie", 21] ``` -- A: Nothing, object are iterable by default +- A: Tidak ada, objek adalah iterable secara default - B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` - C: `*[Symbol.iterator]() { for (let x in this) yield* Object.values(this) }` - D: `*[Symbol.iterator]() { for (let x in this) yield this }` @@ -4744,7 +4741,349 @@ const person = { #### Jawaban: C -Objects aren't iterable by default. An iterable is an iterable if the iterator protocol is present. We can add this manually by adding the iterator symbol `[Symbol.iterator]`, which has to return a generator object, for example by making it a generator function `*[Symbol.iterator]() {}`. This generator function has to yield the `Object.values` of the `person` object if we want it to return the array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. +Objek tidak dapat diulang secara default. Sebuah iterable adalah sebuah iterable jika protokol iterator ada. Kita dapat menambahkan ini secara manual dengan menambahkan simbol iterator + `[Symbol.iterator]`, dimana harus mengembalikan objek generator, sebagai contoh dengan membuat fungsi generator `*[Symbol.iterator]() {}`. Fungsi generator ini harus menghasilkan `Object.values` dari objek `person` jika kita mau mengembalikan array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+ + +--- + +###### 146. Apa yang akan tampil? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Jawaban +

+ +#### Jawaban: C + +Pernyataan `if` didalam perulangan `forEach` akan mengecek apakah nilai dari `num` benar atau salah. Sejak nilai pertama dari array `nums` adalah `0`, yang merupakan nilai salah, pernyataan `if` tidak akan dieksekusi. maka `count` yang mendapat increment hanya untuk 3 nomor yang lain di array `nums`, `1`, `2` dan `3`. sejak `count` mendapat increment `1` 3 kali, maka nilai dari `count` adalah `3`. + +

+
+ +--- + +###### 147. Apa hasilnya? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: A + +Kami mengatur variabel `calc` sama dengan instance baru dari class `Calc`. Kemudian, kami membuat instance baru dari `Calc`, dan memanggil metode `increase` pada contoh ini. Karena properti count berada dalam konstruktor dari class `Calc`, properti count tidak dibagikan pada prototipe `Calc`. Ini berarti bahwa nilai hitungan belum diperbarui untuk contoh yang ditunjukkan kalk, hitung masih `0`. + +

+
+ +--- + +###### 148. Apa hasilnya? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: B + +Fungsi `updateUser` memperbarui nilai properti `email` dan `password` pada pengguna, jika nilainya diteruskan ke fungsi, setelah itu fungsi mengembalikan objek `user`. Nilai yang dikembalikan dari fungsi `updateUser` adalah objek `user`, yang berarti bahwa nilai updatedUser adalah referensi ke objek `user` yang sama dengan yang ditunjuk oleh `user`. `updatedUser === user` sama dengan `true`. + +

+
+ +--- + +###### 149. Apa hasilnya? +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Jawaban +

+ +#### Jawaban: C + +Pertama, kita memanggil metode `slice` pada array fruit. Metode slice tidak mengubah array asli, tetapi mengembalikan nilai yang dipotongnya dari array: banana emoji. +Kemudian, kita memanggil metode `splice` pada array fruit. Metode splice memang mengubah array asli, yang berarti array fruit sekarang terdiri dari `['🍊', '🍎']`. +Akhirnya, kita memanggil metode `unshift` pada array `fruit`, yang memodifikasi array asli dengan menambahkan nilai yang diberikan, ‘🍇’ dalam hal ini, sebagai elemen pertama dalam array. Susunan fruit sekarang terdiri dari `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Apa hasilnya? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: B + +Kunci objek diubah menjadi string. + +Karena nilai `dog` adalah sebuah objek, `animals[dog]`sebenarnya berarti kita membuat properti baru bernama `"object Object"`yang sama dengan objek baru. `animals["object Object"]` sekarang sama dengan `{ emoji: "🐶", name: "Mara"}`. + +`cat` juga merupakan objek, yang berarti bahwa `animals[cat]` sebenarnya berarti bahwa kami menimpa nilai `animals[``"``object Object``"``]` dengan properti cat yang baru. + +Mencatat `animals[dog]`, atau sebenarnya `animals["object Object"]` karena mengonversi objek `dog` menjadi string menghasilkan `"object Object"`, mengembalikan `{emoji: "🐈", nama: "Sara"}`. + +

+
+ +--- + +###### 151. Apa hasilnya? + +```javascript +const user = { + email: "my@email.com", + updateEmail: (email) => { + this.email = email; + }, +}; + +user.updateEmail("new@email.com"); +console.log(user.email); +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Jawaban +

+ +#### Jawaban: A + +Fungsi `updateEmail` adalah fungsi panah, dan tidak terikat ke objek `user`. Artinya, kata kunci `this` tidak merujuk ke objek `user`, tetapi merujuk pada cakupan global dalam kasus ini. Nilai `email` dalam objek `user` tidak diperbarui. Saat memasukkan nilai `user.email`, nilai asli `my@email.com` akan dikembalikan. + +

+
+ +--- + +###### 152. Apa hasilnya? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]); + const res2 = await Promise.all([promise3, promise4]); + return [res1, res2]; +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Jawaban +

+ +#### Jawaban: D + +Metode `Promise.all` menjalankan promise yang diberikan secara paralel. Jika satu promise gagal, metode `Promise.all` dengan nilai promise yang ditolak. Dalam kasus ini, `promise3` ditolak dengan nilai `"Third"`. Kami menangkap nilai yang ditolak dalam metode `catch` yang dirantai pada pemanggilan `runPromises` untuk menangkap setiap kesalahan dalam fungsi `runPromises`. Hanya `"Third"` yang dicatat, karena `promise3` ditolak dengan nilai ini. + +

+
+ +--- + +###### 153.Berapa nilai `method` untuk mencatat `{name: "Lydia", age: 22}`? + +```javascript +const keys = ["name", "age"]; +const values = ["Lydia", 22]; + +const method = + /* ?? */ + Object[method]( + keys.map((_, i) => { + return [keys[i], values[i]]; + }) + ); // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Jawaban +

+ +#### Jawaban: C + +Metode `fromEntries` mengubah array 2d menjadi objek. Elemen pertama di setiap subarray akan menjadi kuncinya, dan elemen kedua di setiap subarray akan menjadi nilainya. Dalam hal ini, kami memetakan di atas array `keys`, yang mengembalikan array yang elemen pertamanya adalah item pada array kunci pada indeks saat ini, dan elemen kedua adalah item dari array nilai pada indeks saat ini. + +Ini membuat array subarray yang berisi kunci dan nilai yang benar, yang menghasilkan `{name:" Lydia ", age: 22}` + +

+
+ +--- + +###### 154. Apa hasilnya? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Jawaban +

+ +#### Jawaban: C + +Nilai default dari `address` adalah objek kosong `{}`. Saat kita menyetel variabel `member` sama dengan objek yang dikembalikan oleh fungsi `createMember`, kita tidak meneruskan nilai untuk address, yang berarti bahwa nilai address adalah objek kosong default `{}`.Objek kosong adalah nilai sebenarnya, yang berarti kondisi `address ? address: null` mengembalikan `true`. Nilai address adalah objek kosong `{}`.

+ +--- + +###### 155. Apa hasilnya? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Jawaban +

+ +#### Jawaban: B + +Kondisi dalam pernyataan `if` memeriksa apakah nilai dari `!typeof randomValue` sama dengan `"string"`. Operator `!` Mengonversi nilai menjadi nilai boolean. Jika nilainya benar, nilai yang dikembalikan akan menjadi `false`, jika nilainya salah, nilai yang dikembalikan akan menjadi `true`. Dalam kasus ini, nilai yang dikembalikan dari `typeof randomValue` adalah nilai sebenarnya `"string"`, artinya nilai `!typeof randomValue` adalah nilai boolean `false`. + +`!typeof randomValue === "string"` selalu mengembalikan false, karena kita sebenarnya memeriksa `false === "string "`. Karena kondisi mengembalikan `false`, blok kode dari pernyataan `else` dijalankan, dan `Yay it's a string!` Akan dicatat. + +

+
+ +--- diff --git a/it-IT/README.md b/it-IT/README.md new file mode 100644 index 00000000..13e465c6 --- /dev/null +++ b/it-IT/README.md @@ -0,0 +1,5122 @@ +
+ +

Domande di JavaScript

+ +--- + +Posto domande a risposta multipla sulle mie [Instagram](https://www.instagram.com/theavocoder) **stories**, che poi posterò anche qui! Ultimo aggiornamento: 23 Maggio + +Da base ad avanzato: metti alla prova quanto conosci JavaScript, rinfresca un po' le tue conoscenze o preparati per il tuo colloquio di programmazione! :muscle: :rocket: Aggiorno regolarmente questo repository con nuove domande. Ho aggiunto le risposte nelle **sezioni compresse** sotto le domande, cliccaci sopra per espanderle. È solo per divertimento, buona fortuna! :heart: + + +Sentiti libero di contattarmi! 😊
+Instagram || Twitter || LinkedIn || Blog +
+ +| Sentiti libero di usarli in un progetto! 😃 Apprezzerei _molto_ un riferimento a questa repository, creo le domande e le spiegazioni (sì, sono triste lol) e la community mi aiuta tantissimo a mantenerlo e migliorarlo! 💪🏼 Grazie e buon divertimento! | + + +Traduzione a cura di: Lucia Cenetiempo +|---| + +--- + +
Vedi le 20 traduzioni disponibili 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Qual è l'output? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` e `undefined` +- B: `Lydia` e `ReferenceError` +- C: `ReferenceError` e `21` +- D: `undefined` e `ReferenceError` + +
+Risposta +

+ +#### Risposta: D + +All'interno della funzione, dichiariamo prima la variabile `name` con la parola chiave `var`. Ciò significa che la variabile viene sollevata all'interno del codice (ovvero lo spazio di memoria viene impostato durante la fase di creazione) e viene inizializzata con il valore predefinito di `undefined`, finché non arriviamo effettivamente alla riga in cui la definiamo. +Al momento in cui proviamo ad eseguire il log della variabile `name` non l'abbiamo ancora dichiarata, quindi mantiene il valore di `undefined`. + +Le variabili dichiarate con la chiave `let` (o `const`) vengono sollevate, ma a differenza delle variabili dichiarate con `var`, non vengono inizializzate. Per questo motivo non sono accessibili prima della loro dichiarazione (dove le inizializzaimo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. + +

+
+ +--- + +###### 2. Qual è l'output? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` e `0 1 2` +- B: `0 1 2` e `3 3 3` +- C: `3 3 3` e `0 1 2` + +
Risposta +

+ +#### Risposta: C + +A causa della coda degli eventi in JavaScript la funzione di callback `setTimeout` viene chiamata _dopo_ che il loop è stato eseguito. Poiché la variabile `i` nel primo loop è stata dichiarata usando la chiave `var`, questo valore è globale. Durante il loop abbiamo incrementato ogni volta il valore di `i` di `1` usando l'operatore unario `++`. Quando è stata invocata la funzione di callback `setTimeout`, `i` nel primo esempio risultava sin dal principio uguale a `3`. + +Nel secondo loop, la variabile `i` è stata dichiarata usando la chiave `let`: le variabili dichiarate con la chiave `let` (e `const`) hanno lo scope del blocco (un blocco è qualsiasi cosa tra `{ }`). Durante ogni iterazione, `i` avrà un nuovo valore e ogni valore avrà lo scope all'interno del loop. + +

+
+ +--- + +###### 3. Qual è l'output? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` e `62.83185307179586` +- B: `20` e `NaN` +- C: `20` e `63` +- D: `NaN` e `63` + +
Risposta +

+ +#### Risposta: B + +Il valore di `diameter` è una funzione regolare, mentre il valore di `perimeter` è generato con una arrow function. + +Nelle arrow functions, la chiave `this` fa riferimento al suo scope interno a differenza delle funzioni regolari. Questo vuol dire che quando richiamiamo `perimeter` non stiamo facendo riferimento all'oggetto shape, ma al suo ambito circostante (ad esempio window). + +Non troviamo quindi alcun valore `radius` in quell'oggetto e quindi viene restituito `NaN`. + +

+
+ +--- + +###### 4. Qual è l'output? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Risposta +

+ +#### Risposta: A + +Il + unario tenta di convertire un operando in un numero. `true` equivale ad `1` e `false` equivale a `0`. + +La stringa `'Lydia'` è un valore veritiero. Quello che in realtà ci stiamo chiedendo con `!'Lydia'` è "questo valore veritiero è falso?". Per cui la risposta è `false`. + +

+
+ +--- + +###### 5. Quale affermazione è vera? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` non è valido +- B: `mouse[bird.size]` non è valido +- C: `mouse[bird["size"]]` non è valido +- D: Sono tutte valide + +
Risposta +

+ +#### Risposta: A + +In JavaScript, tutte le chiavi degli oggetti sono stringhe (a meno che non sia un simbolo). Anche se potremmo non scriverle come stringhe, vengono sempre convertite come tali. + +JavaScript interpreta le istruzioni, quindi quando usiamo la bracket notation, vede la prima parentesi aperta `[` e continua finché non trova la parentesi chiusa `]`. Solo allora valuterà la dichiarazione. + +Quando in JavaScript richiamiamo `mouse[bird.size]`: per prima cosa viene valorizzato `bird.size`, che è `"small"`, per JS viene tradotto quindi come `mouse["small"]` che restituisce `true`. + +Con l'utilizzo del punto questo non accade perché `mouse` non ha una chiave chiamata `bird`, e questo significa che `mouse.bird` è `undefined`. Per JavaScript quindi l'istruzione `mouse.bird.size` viene tradotta con `mouse.undefined.size` che è un valore non valido e che quindi genererà un errore simile a `Cannot read property "size" of undefined`. + +

+
+ +--- + +###### 6. Qual è l'output? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Risposta +

+ +#### Risposta: A + +In JavaScript, tutti gli oggetti interagiscono per _referenza_. + +La variabile `c` contiene come valore un oggetto. Alla variabile `d` assegniamo come valore il riferimento di `c` che quindi contiene l'oggetto (e non un suo clone). + + + +Quando modifichi il valore di questo oggetto, lo stai modificando sia per `c`che per `d`, che contiene il suo riferimento. + +

+
+ +--- + +###### 7. Qual è l'output? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Risposta +

+ +#### Risposta: C + +`new Number()` è una funzione costruttore integrata. Nonostante sembri un numero, in realtà non lo è, si tratta infatti di un oggetto con un sacco di funzioni extra. + +Quando utilizziamo l'operatore `==`, stiamo verificando solo se il suo _valore_ è uguale. Entrambe le variabili hanno il valore di `3`, quindi il primo log restituisce `true`. + +Quando invece utilizziamo l'operatore `===`, stiamo verificando che sia il valore che il tipo di valore siano uguali. `new Number()` non è un numero, è un **oggetto** quindi entrambi i log restituiscono `false`. + +

+
+ +--- + +###### 8. Qual è l'output? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: D + +La funzione `colorChange` è statica. I metodi statici sono progettati per vivere solo nel costruttore in cui vengono creati e non possono essere passati a nessun figlio o richiamati su istanze di classe. Poiché `freddie` è un'istanza della classe `Chameleon`, la funzione non può essere chiamata su di essa. Viene restituito quindi un errore di tipo `TypeError`. + +

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

+ +#### Risposta: A + +Il nostro log restituisce un oggetto perché abbiamo appena creato un oggetto vuoto come oggetto globale nel momento in cui per errore abbiamo digitato `greetign` al posto di `greeting`. + +Il nostro interprete a quel punto ha letto `global.greetign = {}` (o `window.greetign = {}` se parliamo di un browser). + +Per evitare ciò, possiamo usare `"use strict"`. Questo assicura di aver dichiarato una variabile prima di impostarla uguale a qualsiasi cosa. + +

+
+ +--- + +###### 10. Cosa succede se facciamo questo? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Niente, va benissimo! +- B: `SyntaxError`. Non è possibile aggiungere proprietà a una funzione in questo modo. +- C: `"Woof"` viene registrato. +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +In JavaScript non succede nulla, perché le funzioni sono oggetti! (Tutto tranne i tipi primitivi sono oggetti). + +Una funzione è un tipo speciale di oggetto. Il codice che scrivi non è la funzione effettiva. La funzione è un oggetto con delle proprietà e quindi questa proprietà è invocabile. + +

+
+ +--- + +###### 11. Qual è l'output? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Risposta +

+ +#### Risposta: A + +In JavaScript, le funzioni sono oggetti e quindi il metodo `getFullName` viene aggiunto al costruttore della funzione stessa. Per questo motivo possiamo chiamare `Person.getFullName()`, mentre `member.getFullName` genera un `TypeError`. + +Se vuoi che un metodo sia disponibile per tutte le istanze dell'oggetto, devi aggiungerlo alla proprietà del prototipo: + + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Qual è l'output? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Per la const `sarah`, non abbiamo usato la chiave `new`. Quando si usa `new`, `this` si riferisce al nuovo oggetto vuoto che creiamo. Tuttavia, se non aggiungiamo `new`, `this` si riferisce all'**oggetto globale**! + +Abbiamo quindi scritto che `this.firstName` equivale a `"Sarah"` e `this.lastName` equivale a `"Smith"`. Quello che abbiamo effettivamente fatto è definire `global.firstName = 'Sarah'` e `global.lastName = 'Smith'`. La `const` `sarah` viene lasciata come `non definita`, perché non restituiamo un valore dalla funzione `Persona`. + +

+
+ +--- + +###### 13. Quali sono le tre fasi della propagazione degli eventi? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Risposta +

+ +#### Risposta: D + +Durante la fase di **capturing**, l'evento passa attraverso gli elementi predecessori fino all'elemento target. Quindi raggiunge l'elemento **target** e inizia il **bubbling**. + + + +

+
+ +--- + +###### 14. Tutti gli oggetti hanno prototipi. + +- A: true +- B: false + +
Risposta +

+ +#### Risposta: B + +Tutti gli oggetti hanno prototipi, ad eccezione dell'**oggetto base**. L'oggetto base è l'oggetto creato dall'utente, o un oggetto creato usando la parola chiave `new`. L'oggetto base ha accesso ad alcuni metodi e proprietà, come `.toString`. Questo è il motivo per cui puoi utilizzare i metodi JavaScript built-in! Tutti questi metodi sono disponibili sul prototype. Quindi, anche se JavaScript non riesce a trovarlo direttamente sul tuo oggetto, scende lungo la chain del prototype e lo trova lì, il che lo rende accessibile anche per l'oggetto creato da te. + +

+
+ +--- + +###### 15. Qual è l'output? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Risposta +

+ +#### Risposta: C + +JavaScript è un **linguaggio tipizzato dinamicamente**: non specifichiamo quali tipi siano determinate variabili. I valori possono essere automaticamente convertiti in un altro tipo, questa azione è chiamata _coercizione implicita del tipo_. **Coercizione** è la conversione da un tipo all'altro. + +In questo esempio, JavaScript converte il numero `1` in una stringa, in modo che la funzione abbia un senso e restituisca un valore. Durante l'aggiunta di un tipo numerico (`1`) e di un tipo stringa (`'2'`), il numero viene trattato come una stringa. Possiamo concatenare stringhe come `"Hello" + "World"`, quindi quello che sta succedendo qui è `"1" + "2"` che restituisce `"12"`. + +

+
+ +--- + +###### 16. Qual è l'output? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Risposta +

+ +#### Risposta: C + +Utilizzando l'operatore unario come **postfisso** `number++` succede che: + +1. Restituisce prima il suo valore (`0`) +2. Subito dopo incrementa il valore di 1 (quindi è ora `1`) + +Utilizzando l'operatore unario come **prefisso** `++number` succede che: + +1. Incrementa prima il valore (il numero è ora `2`) +2. Restituisce subito dopo il valore già incrementato (`2`) + +Quindi il nostro log sarà `0 2 2`. + +

+
+ +--- + +###### 17. Qual è l'output? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Risposta +

+ +#### Risposta: B + +Utilizzando i template literals, il valore del primo argomento sarà un array di valori della stringa. Gli altri argomenti prenderanno i valori dell'espressione passata. + +

+
+ +--- + +###### 18. Qual è l'output? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Risposta +

+ +#### Risposta: C + +Quando si verifica l'uguaglianza, i primitivi vengono confrontati in base al loro _valore_, mentre gli oggetti vengono confrontati in base al loro _riferimento_. JavaScript controlla se gli oggetti hanno un riferimento alla stessa posizione in memoria. + +I due oggetti che stiamo confrontando non lo hanno: l'oggetto che abbiamo passato come parametro si riferisce a una posizione di memoria diversa rispetto all'oggetto che abbiamo usato per verificare l'uguaglianza. + +Questo è il motivo per cui sia `{ age: 18 } === { age: 18 }` e `{ age: 18 } == { age: 18 }` restituiscono `false`. + +

+
+ +--- + +###### 19. Qual è l'output? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Risposta +

+ +#### Risposta: C + +Il parametro rest (`...args`) ci permette di "collettare" tutti gli argomenti in un array. L'array è un oggetto, quindi `typeof args` restituisce `"oggetto"` + +

+
+ +--- + +###### 20. Qual è l'output? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: C + +Con `"use strict"`, puoi assicurarti di non dichiarare variabili globali per sbaglio. In questo caso la variabile `age` non è mai stata dichiarata, e siccome usiamo `"use strict"`, genererà un `ReferenceError`. Se non avessimo usato `"use strict"`, avrebbe funzionato perché la proprietà `age` sarebbe stata aggiunta all'oggetto globale. + +

+
+ +--- + +###### 21. Qual è il valore di `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Risposta +

+ +#### Risposta: A + +`eval` "valuta" i codici passati come stringa. Se è un'espressione, come in questo caso, valuta l'espressione. L'espressione è `10 * 10 + 5`. Quindi il valore restituito è il numero `105`. + +

+
+ +--- + +###### 22. Per quanto tempo cool_secret è accessibile? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Per sempre, i dati non vanno persi. +- B: Fin quando l'utente chiude la scheda. +- C: Fin quando l'utente chiude l'intero browser, non solo la scheda. +- D: Fin quando l'utente spegne il proprio computer. + +
Risposta +

+ +#### Risposta: B + +I dati memorizzati in `sessionStorage` vengono rimossi dopo aver chiuso la _tab_. + +Se avessi usato `localStorage`, i dati sarebbero rimasti lì per sempre, a meno che, ad esempio, non fosse stato invocato `localStorage.clear()`. + +

+
+ +--- + +###### 23. Qual è l'output? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con la chiave `var` puoi dichiarare più variabili con lo stesso nome. La variabile conterrà quindi l'ultimo valore. + +Non puoi farlo con `let` o `const` poiché sono block-scoped. + +

+
+ +--- + +###### 24. Qual è l'output? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Risposta +

+ +#### Risposta: C + +Tutte le chiavi degli oggetti (esclusi i simboli) sono stringhe, anche se non vengono scritte come tali. Questo è il motivo per cui anche `obj.hasOwnProperty('1')` restituisce true. + +Per i set non funziona allo stesso modo degli oggetti. Non c'è alcun `'1'` nel nostro set, per cui `set.has('1')` restituisce `false`, è però presente il tipo numerico `1` per cui `set.has(1)` restituisce `true`. + +

+
+ +--- + +###### 25. Qual è l'output? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: C + +Se hai due chiavi con lo stesso nome, questa verrà sostituita. Sarà quindi ancora nella sua prima posizione, ma con l'ultimo valore specificato. + +

+
+ +--- + +###### 26. Il contesto di esecuzione globale JavaScript crea due cose: l'oggetto globale e la parola chiave "this". + +- A: true +- B: false +- C: it depends + +
Risposta +

+ +#### Risposta: A + +Il contesto di esecuzione di base è il contesto di esecuzione globale: è ciò che è accessibile ovunque nel codice. + +

+
+ +--- + +###### 27. Qual è l'output? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Risposta +

+ +#### Risposta: C + +L'istruzione `continue` salta un'iterazione se una certa condizione restituisce `true`. + +

+
+ +--- + +###### 28. Qual è l'output? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: A + +`String` è un costruttore built-in, a cui possiamo aggiungere proprietà. In questo caso è stato appena aggiunto un metodo al suo prototipo. +Le stringhe primitive vengono automaticamente convertite in un oggetto stringa, generato dalla string prototype function. Quindi, tutte le stringhe hanno accesso a quel metodo! + +

+
+ +--- + +###### 29. Qual è l'output? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Le chiavi degli oggetti vengono automaticamente convertite in stringhe. Stiamo cercando di impostare un oggetto come chiave per l'oggetto `a` con il valore di `123`. + +Tuttavia, quando convertiamo in stringa un oggetto, diventa `"[object Object]"`. Quindi quello che stiamo dicendo qui è che `a["[object Object]"] = 123`. `c` è un altro oggetto che stiamo implicitamente stringendo. Quindi, `a["[object Object]"] = 456`. + +Quindi, quando facciamo console.log di `a[b]`, che in realtà è `a["[object Object]"]` che abbiamo appena valorizzato con `456`, restituisce `456`. + +

+
+ +--- + +###### 30. Qual è l'output? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Risposta +

+ +#### Risposta: B + +Abbiamo una funzione `setTimeout` e l'abbiamo invocata per prima. Eppure, viene loggata per ultima. + +Questo succede perché nei browser non abbiamo solo il runtime engine, ma anche qualcosa chiamata `WebAPI`. La `WebAPI` ci fornisce la funzione `setTimeout` con cui iniziare, e per esempio il DOM. + +Dopo che la _callback_ è stata inviata alla `WebAPI`, la stessa funzione `setTimeout` (ma non la sua callback) viene eliminata dallo stack. + + + +Ora, `foo` viene invocato e `"First"` viene loggato. + + + +`foo` viene quindi tolto dallo stack e `baz` viene invocato. `"Third"` viene loggato. + + + +La WebAPI non può semplicemente aggiungere elementi allo stack ogni volta che è pronta, spinge quindi la funzione di callback in quella che chiamiamo _queue_. + + + +È qui che un ciclo di eventi inizia a funzionare. Un **event loop** esamina lo stack e la coda delle attività. Se lo stack è vuoto, prende la prima cosa in coda e la inserisce nello stack. + + + +`bar` viene invocato, `"Second"` viene registrato e viene tolto dallo stack. + +

+
+ +--- + +###### 31. Quale sarà event.target cliccando sul bottone? + +```html +
+
+ +
+
+``` + +- A: `div` esterno +- B: `div` interno +- C: `button` +- D: Un array di tutti gli elementi nidificati + +
Risposta +

+ +#### Risposta: C + +L'elemento annidato più in profondità è quello che ha causato l'evento ed è quindi l'event.target. Puoi stoppare la propagazione con `event.stopPropagation` + +

+
+ +--- + +###### 32. Cliccando sul paragrafo, quale sarà l'output loggato? + +```html +
+

+ Click here! +

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

+ +#### Risposta: A + +Se clicchiamo su `p`, vediamo due log: `p` e `div`. Durante la propagazione dell'evento, ci sono 3 fasi: capturing, target, e bubbling. Di default, i gestori di eventi vengono eseguiti nella fase di bubbling (a meno che non si imposti `useCapture` su `true`) e va quindi dall'elemento annidato più profondo verso l'esterno. + +

+
+ +--- + +###### 33. Qual è l'output? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Risposta +

+ +#### Risposta: D + +Con entrambi possiamo passare l'oggetto a cui vogliamo che la chiave `this` faccia riferimento. Tuttavia, anche `.call` viene _eseguito immediatamente_! + +`.bind.` restituisce una _copia_ della funzione, ma con un contesto vincolato! Non viene eseguito immediatamente. + +

+
+ +--- + +###### 34. Qual è l'output? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Risposta +

+ +#### Risposta: B + +La funzione `sayHi` restituisce il valore dato dell'espressione della immediately invoked function expression (IIFE). Questa funzione ha restituito `0`, che è di tipo `"numero"`. + +Ci sono solo 7 tipi built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object` e `symbol`. `"function"` non è un tipo, poiché le funzioni sono oggetti, è quindi di tipo "oggetto"`. + +

+
+ +--- + +###### 35. Quale di questi valori è falso? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Sono tutti falsi + +
Risposta +

+ +#### Risposta: A + +Ci sono 8 valori falsi: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) + +I costruttori di funzioni, come `new Number` e `new Boolean` sono veritieri. + +

+
+ +--- + +###### 36. Qual è l'output? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Risposta +

+ +#### Risposta: B + +`typeof 1` ritorna `"number"`. +`typeof "number"` ritorna `"string"` + +

+
+ +--- + +###### 37. Qual è l'output? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, 7 x null, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, 7 x empty, 11]` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: C + +Quando imposti un valore su un elemento in un array che supera la lunghezza dell'array JavaScript crea degli "slot vuoti". Questi in realtà hanno il valore di `undefined`, ma vedrai qualcosa come: + +`[1, 2, 3, 7 x empty, 11]` + +a seconda di dove lo esegui (è diverso per ogni browser, node, ecc.) + +

+
+ +--- + +###### 38. Qual è l'output? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: A + +Il blocco `catch` riceve l'argomento `x` ma non è la stessa `x` della variabile, bensì passiamo un argomento della funzione. Questa "variabile" `x` è block-scoped quindi ha un ambito di blocco. + +Subito dopo impostiamo il valore di variabile block-scoped a `1` e impostiamo il valore della variabile `y`. Ora facciamo un console.log della variabile block-scoped `x`, che è uguale a `1`. + +Fuori dal blocco `catch`, `x` è ancora `undefined` e `y` è `2` quindi quando facciamo `console.log(x)` al di fuori del blocco `catch`, otterremo `undefined` e `y` restituirà `2`. + +

+
+ +--- + +###### 39. Tutto in JavaScript è... + +- A: o un primitivo o un oggetto +- B: o una funzione o un oggetto +- C: Questa è una domanda trabocchetto! Sono solo oggetti +- D: un numero o un oggetto + +
Risposta +

+ +#### Risposta: A + +JavaScript ha solo tipi primitivi e oggetti. + +I tipi primitivi sono `boolean`, `null`, `undefined`, `bigint`, `number`, `string` e `symbol`. + +Ciò che differenzia un tipo primitivo da un oggetto è che i primitivi non hanno proprietà o metodi. Tuttavia, noterai che `'foo'.toUpperCase()` restituisce `'FOO'` e non genera un `TypeError`. Questo perché quando si tenta di accedere a una proprietà o a un metodo su di un tipo primitivo come lo è una stringa, JavaScript racchiuderà implicitamente il tipo primitivo utilizzando una delle classi wrapper, ovvero "String", valuterà l'espressione ed eliminerà il wrapper una volta terminato. Tutti i primitivi tranne `null` e `undefined` subiscono questo comportamento. + +

+
+ +--- + +###### 40. Qual è l'output? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Risposta +

+ +#### Risposta: C + +`[1, 2]` rappresenta il nostro valore interno. Ovvero il valore con cui iniziamo e il valore del primo `acc`. Durante il primo round, `acc` è `[1,2]` e `cur` è `[0, 1]`. Li concateniamo ottenendo `[1, 2, 0, 1]`. + +A questo punto `acc` corrisponderà a `[1, 2, 0, 1]` e `cur` sarà ancora `[2, 3]`. Li concateniamo e otteniamo `[1, 2, 0, 1, 2, 3]` +

+
+ +--- + +###### 41. Qual è l'output? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Risposta +

+ +#### Risposta: B + +`null` è falso. `!null` restituisce `true`. `!true` restituisce `false`. + +`""` è falso. `!""` restituisce `true`. `!true` restituisce `false`. + +`1` è vero. `!1` restituisce `falso`. `!false` restituisce `true`. + +

+
+ +--- + +###### 42. Cosa restituisce il metodo `setInterval` nel browser? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: un ID univoco +- B: la quantità di millisecondi specificata +- C: la funzione passata +- D: `undefined` + +
Risposta +

+ +#### Risposta: A + +Restituisce un ID univoco. Questo id può essere usato per cancellare quell'intervallo con la funzione `clearInterval()`. + +

+
+ +--- + +###### 43. Cosa restituisce? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Risposta +

+ +#### Risposta: A + +Una stringa è un iterabile. L'operatore spread mappa ogni carattere di una stringa rendendola parte di array. + +

+
+ +--- + +###### 44. Qual è l'output? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Risposta +

+ +#### Risposta: C + +Le funzioni regolari non possono essere interrotte a metà dopo l'invocazione. Tuttavia, una funzione "generator" può essere stoppata a metà e in seguito continuare da dove si era interrotta. Ogni volta che una funzione generator incontra una parola chiave `yield`, la funzione restituisce il valore specificato dopo di essa. Nota che la funzione del generator in quel caso non _restituisce (return)_ il valore, _rende (yeld)_ il valore. + +Come prima cosa inizializziamo la funzione del generator con `i` uguale a `10`. Invochiamo la funzione usando il metodo `next()`. La prima volta che invochiamo la funzione generator, `i` è uguale a `10`, incontra la prima parola chiave `yield` quindi restituisce il valore di `i`. Il generatore è ora "in pausa" e `10` viene loggato. + +Invochiamo di nuovo la funzione con il metodo `next()`. Inizia a continuare da dove si era fermata in precedenza, sempre con `i` uguale a `10`. Ora incontra il secondo `yield` e restituisce `i * 2`, quindi restituisce `10 * 2`, che è `20`. Ciò risulta in `10, 20`. + +

+
+ +--- + +###### 45. Cosa restituisce? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Risposta +

+ +#### Risposta: B + +Quando passiamo più promises al metodo `Promise.race`, questo risolve/rifiuta la _prima_ promise. Al metodo `setTimeout` passiamo un timer: 500ms per la prima promise (`firstPromise`) e 100ms per la seconda promise (`secondPromise`). Ciò significa che `secondPromise` si risolve prima con il valore di `'due'`. `res` ora contiene il valore di `'two'`, che viene loggato. + +

+
+ +--- + +###### 46. Qual è l'output? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Risposta +

+ +#### Risposta: D + +Per prima cosa, dichiariamo una variabile `person` con un oggetto che ha una proprietà `name`. + + + +Quindi, dichiariamo una variabile chiamata `members`. Impostiamo il primo elemento di quell'array uguale al valore della variabile `person`. Gli oggetti interagiscono per _riferimento_ quando vengono impostati uguali tra loro. Quando assegni un riferimento da una variabile all'altra, esegui una _copia_ di quel riferimento. (nota che non hanno lo _stesso_ riferimento!) + + + +Quindi, impostiamo la variabile `person` uguale a `null`. + + + +Stiamo modificando solo il valore della variabile `person`, e non il primo elemento nell'array, poiché quell'elemento ha un riferimento diverso (copiato) dall'oggetto. Il primo elemento in `members` mantiene ancora il suo riferimento all'oggetto originale. Quando logghiamo l'array `members`, il primo elemento contiene ancora il valore dell'oggetto, che viene loggato. + +

+
+ +--- + +###### 47. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Risposta +

+ +#### Risposta: B + +Con il ciclo `for-in`, possiamo iterare le chiavi degli oggetti, in questo caso `name` e `age`. Le chiavi degli oggetti sono stringhe (se non sono un simbolo). In ogni ciclo, impostiamo il valore di `item` uguale alla chiave corrente su cui sta iterando. Il primo `item` è uguale a `name` e viene loggato, `item` sarà poi uguale a `age`, che viene loggato. + +

+
+ +--- + +###### 48. Qual è l'output? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Risposta +

+ +#### Risposta: B + +L'associazione è l'ordine in cui il compilatore valuta le espressioni, da sinistra a destra o da destra a sinistra. Questo accade solo se tutti gli operatori hanno la _stessa_ precedenza. Abbiamo solo un tipo di operatore: `+`. Inoltre, l'associazione è da sinistra a destra. + +`3 + 4` viene valutato per primo. E risulta nell'addizione dei due valori che restituiscono quindi `7`. + +`7 + '5'` risulta in `"75"` per via della coercizione. JavaScript converte il numero `7` in una stringa, (vedi la domanda 15). Possiamo concatenare due stringhe usando l'operatore `+`. `"7" + "5"` risulta quindi in "75"`. + +

+
+ +--- + +###### 49. Qual è il valore di `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Risposta +

+ +#### Risposta: C + +Viene restituito solo il primo valore della stringa. In base alla _radice_ (ovvero il secondo argomento per specificare sulla base di quale tipo di numero vogliamo analizzarlo: base 10, esadecimale, ottale, binario, ecc.), `parseInt` controlla se i caratteri nella stringa sono validi. Una volta che incontra un carattere che non è un numero valido nella radice, interrompe l'analisi e ignora i seguenti caratteri. + +`*` non è un numero valido. Analizza solo `"7"` nel decimale `7`. `num` ora contiene il valore di `7`. + +

+
+ +--- + +###### 50. Qual è l'output? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Risposta +

+ +#### Risposta: C + +Quando si esegue il mapping sull'array, il valore di `num` è uguale all'elemento su cui sta attualmente scorrendo. In questo caso, gli elementi sono numeri, quindi la condizione dell'istruzione if `typeof num === "number"` restituisce `true`. La funzione map crea un nuovo array e inserisce i valori restituiti dalla funzione. + +Tuttavia, non ritorniamo un valore. Quando non ritorniamo un valore dalla funzione, la funzione restituisce `undefined`. Per ogni elemento nell'array, viene chiamato il blocco funzione, quindi per ogni elemento restituiamo `undefined`. + +

+
+ +--- + +###### 51. Qual è l'output? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Risposta +

+ +#### Risposta: A + +Gli argomenti vengono passati come _valori_, a meno che il loro valore non sia un oggetto, quindi vengono passati come _reference_. `birthYear` viene passato per valore, poiché è una stringa, non un oggetto. Quando passiamo argomenti per valore, viene creata una _copia_ di quel valore (vedi domanda 46). + +La variabile `birthYear` ha un riferimento al valore `"1997"`. Anche l'argomento `year` fa riferimento al valore `"1997"`, ma non è lo stesso valore a cui fa riferimento `birthYear`. Quando aggiorniamo il valore di `year` impostando `year` uguale a `"1998"`, stiamo solo aggiornando il valore di `year`. `birthYear` è ancora uguale a `"1997"`. + +Il valore di `person` è un oggetto. L'argomento `member` ha un riferimento (copiato) dello stesso oggetto. Quando modifichiamo una proprietà dell'oggetto a cui `member` fa riferimento, verrà modificato anche il valore di `person`, poiché entrambi hanno un riferimento allo stesso oggetto. La proprietà `name` di `person` è ora uguale al valore `"Lydia"` +

+
+ +--- + +###### 52. Qual è l'output? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Risposta +

+ +#### Risposta: D + +Con l'istruzione `throw`, possiamo creare errori personalizzati. Con questa istruzione, puoi generare eccezioni. Un'eccezione può essere una stringa, un numero, un booleano o un oggetto. In questo caso, la nostra eccezione è la stringa `'Hello world!'`. + +Con l'istruzione `catch`, possiamo specificare cosa fare se viene generata un'eccezione nel blocco `try`. Viene generata un'eccezione: la stringa `'Hello world!'`. `e` è ora uguale a quella stringa, che logghiamo. Ciò si traduce in `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Qual è l'output? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: B + +Quando si restituisce una proprietà, il valore della proprietà è uguale al valore _restituito_, non al valore impostato nella funzione di costruzione. Restituiamo la stringa `"Maserati"`, quindi `myCar.make` è uguale a `"Maserati"`. + +

+
+ +--- + +###### 54. Qual è l'output? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Risposta +

+ +#### Risposta: A + +`let x = (y = 10);` in realtà è un'abbreviazione per: + +```javascript +y = 10; +let x = y; +``` + +Quando impostiamo `y` uguale a `10`, in realtà aggiungiamo una proprietà `y` all'oggetto globale (`window` nel browser, `global` in Node). In un browser, `window.y` ora è uguale a `10`. + +Quindi, dichiariamo una variabile `x` con il valore di `y`, che è `10`. Le variabili dichiarate con la parola chiave `let` sono _block scoped_, ovvero sono definite solo all'interno del blocco in cui sono dichiarate, l'espressione di funzione immediatamente invocata (IIFE) in questo caso. Quando utilizziamo l'operatore `typeof`, l'operando `x` non è definito: stiamo cercando di accedere a `x` al di fuori del blocco in cui è dichiarato. Ciò significa che `x` non è definito. I valori a cui non è stato assegnato un valore o dichiarati sono di tipo `"undefined"`. `console.log(typeof x)` restituisce `"undefined"`. + +Tuttavia, abbiamo creato una variabile globale `y` quando abbiamo impostato `y` uguale a `10`. Questo valore è accessibile ovunque nel nostro codice. `y` è definito e contiene un valore di tipo `"number"`. `console.log(typeof y)` restituisce `"number"`. + +

+
+ +--- + +###### 55. Qual è l'output? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Risposta +

+ +#### Risposta: A + +Possiamo eliminare le proprietà dagli oggetti usando la parola chiave `delete`, anche sul prototype. Eliminando una proprietà sul prototipo, questa non è più disponibile nella catena di prototype. In questo caso, la funzione `bark` non è più disponibile sul prototipo dopo `delete Dog.prototype.bark`, ma proviamo comunque ad accedervi. + +Quando proviamo a invocare qualcosa che non è una funzione, viene lanciato un `TypeError`. In questo caso `TypeError: pet.bark is not a function`, poiché `pet.bark` è `undefined`. + +

+
+ +--- + +###### 56. Qual è l'output? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Risposta +

+ +#### Risposta: D + +L'oggetto `Set` è una collezione di valori _unici_: un valore può verificarsi solo una volta in un set. + +Abbiamo passato l'array `[1, 1, 2, 3, 4]` con il valore duplicato `1`. Poiché non possiamo avere due valori uguali in un set, uno di essi viene rimosso. Ciò risulta in `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Qual è l'output? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Risposta +

+ +#### Risposta: C + +Un modulo importato è di _sola lettura_: non è quindi possibile modificare il modulo importato. Solo il modulo che li esporta può cambiarne il valore. + +Quando proviamo ad incrementare il valore di `myCounter`, viene generato un errore: perché `myCounter` è di sola lettura e non può essere modificato. + +

+
+ +--- + +###### 58. Qual è l'output? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Risposta +

+ +#### Risposta: A + +L'operatore `delete` restituisce un valore booleano: `true` su una cancellazione riuscita, altrimenti restituirà `false`. Tuttavia, le variabili dichiarate con la parola chiave `var`, `const` o `let` non possono essere cancellate usando l'operatore `delete`. + +La variabile `name` è stata dichiarata con la chiave `const`, quindi la sua cancellazione non va a buon fine e viene restituito `false`. Quando impostiamo `age` uguale a `21`, abbiamo effettivamente aggiunto una proprietà chiamata `age` all'oggetto globale. Puoi eliminare con successo le proprietà dagli oggetti in questo modo, anche l'oggetto globale, quindi `delete age` restituisce `true`. + +

+
+ +--- + +###### 59. Qual è l'output? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Risposta +

+ +#### Risposta: C + +Possiamo spacchettare i valori da un array o proprietà dagli oggetti attraverso la destrutturazione. Per esempio: + +```javascript +[a, b] = [1, 2]; +``` + + + +Il valore di `a` ora è `1`, e il valore di `b` è ora `2`. Quello che abbiamo effettivamente fatto nella domanda è: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Questo significa che il valore di `y` è uguale al primo valore nell'array, che è il numero `1`. Quando registriamo `y`, viene restituito `1`. + +

+
+ +--- + +###### 60. Qual è l'output? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Risposta +

+ +#### Risposta: B + +È possibile combinare oggetti utilizzando l'operatore spread `...`. Questo ti consente di creare copie delle coppie chiave/valore di un oggetto e aggiungerle a un altro oggetto. In questo caso, creiamo copie dell'oggetto `user` e le aggiungiamo all'oggetto `admin`. L'oggetto `admin` ora contiene le coppie chiave/valore copiate, che risultano in `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. Qual è l'output? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Risposta +

+ +#### Risposta: B + +Con il metodo `defineProperty`, possiamo aggiungere nuove proprietà a un oggetto o modificare quelle esistenti. Quando aggiungiamo delle proprietà a un oggetto usando il metodo `defineProperty`, queste per impostazione predefinita sono _non enumerabili_. Il metodo `Object.keys` restituisce tutti i nomi di proprietà _enumerabili_ da un oggetto, in questo caso solo `"name"`. + +Le proprietà aggiunte usando il metodo `defineProperty` sono immutabili per impostazione predefinita. Puoi ignorare questo comportamento usando le proprietà `writable`, `configurable` ed `enumerable`. In questo modo, il metodo `defineProperty` ti dà molto più controllo sulle proprietà che stai aggiungendo a un oggetto. + +

+
+ +--- + +###### 62. Qual è l'output? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Risposta +

+ +#### Risposta: A + +Il secondo argomento di `JSON.stringify` è _replacer_. Il replacer può essere una funzione o un array e consente di controllare cosa e come i valori devono essere stringati. + +Se il replacer è un _array_, solo i nomi delle proprietà inclusi nell'array verranno aggiunti alla stringa JSON. In questo caso, sono incluse solo le proprietà con i nomi `"level"` e `"health"`, `"username"` è esclusa. `data` quindi ora è uguale a `"{"level":19, "health":90}"`. + +Se il replacer è una _funzione_, questa funzione viene chiamata su ogni proprietà nell'oggetto che stai stringendo. Il valore restituito da questa funzione sarà il valore della proprietà quando viene aggiunto alla stringa JSON. Se il valore è `undefined`, questa proprietà viene esclusa dalla stringa JSON. + +

+
+ +--- + +###### 63. Qual è l'output? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Risposta +

+ +#### Risposta: A + +L'operatore unario `++` _prima_ restituisce il valore dell'operando, _poi_ incrementa il valore dell'operando. Il valore di `num1` è `10`, poiché la funzione `increaseNumber` restituisce prima il valore di `num`, che è `10`, e solo successivamente incrementa il valore di `num`. + +`num2` è `10`, poiché abbiamo passato `num1` a `increasePassedNumber`. `number` è uguale a `10` (il valore di `num1`. Anche in questo caso, l'operatore unario `++` _prima_ restituisce il valore dell'operando, _poi_ lo incrementa. Il valore di `number` è ` 10`, quindi `num2` è uguale a `10`. + +

+
+ +--- + +###### 64. Qual è l'output? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Risposta +

+ +#### Risposta: C + +In ES6, possiamo inizializzare i parametri con un valore predefinito. Il valore del parametro sarà il valore predefinito se nessun altro valore è stato passato alla funzione o se è stato passato un valore `"undefined"`. In questo caso, distribuiamo le proprietà dell'oggetto `value` in un nuovo oggetto, quindi `x` ha il valore predefinito di `{ number: 10 }`. + +L'argomento predefinito viene valutato quando viene chiamato! Ogni volta che chiamiamo la funzione, viene creato un _nuovo_ oggetto. Invochiamo la funzione `multiply` le prime due volte senza passare un valore, quindi `x` ha il valore predefinito di `{ number: 10 }`. Quindi logghiamo il valore moltiplicato di quel numero, che è `20`. + +La terza volta che invochiamo la funzione multiply, passiamo un argomento: l'oggetto chiamato `value`. L'operatore `*=` è in realtà un'abbreviazione per `x.number = x.number * 2`: modifichiamo il valore di `x.number` e logghiamo il valore moltiplicato `20`. + +La quarta volta, passiamo di nuovo l'oggetto `value`, in questo caso `x.number` è stato precedentemente modificato in `20`, quindi `x.number *= 2` logga `40`. + +

+
+ +--- + +###### 65. Qual è l'output? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Risposta +

+ +#### Risposta: D + +Il primo argomento che il metodo `reduce` riceve è l'_accumulatore_, in questo caso `x`. Il secondo argomento è il _valore corrente_ `y`. +Con il metodo reduce, eseguiamo una funzione di callback su ogni elemento dell'array, che alla fine potrebbe risultare in un singolo valore. + +In questo esempio, non stiamo restituendo alcun valore, stiamo semplicemente loggando i valori dell'accumulatore e il valore corrente. + +Il valore dell'accumulatore è uguale al valore restituito in precedenza dalla funzione di callback. Se non si passa l'argomento opzionale `initialValue` al metodo `reduce`, l'accumulatore è uguale al primo elemento della prima chiamata. + +Alla prima chiamata, l'accumulatore (`x`) è `1` e il valore corrente (`y`) è `2`. Non facciamo un return con la funzione di callback ma logghiamo l'accumulatore e il valore corrente: `1` e `2` vengono loggati. + +Se non restituisci un valore da una funzione questa restituisce `undefined`. Alla chiamata successiva, l'accumulatore è `undefined` e il valore corrente è "3". `undefined` e `3` vengono loggati. + +Alla quarta chiamata, di nuovo non facciamo un return dalla funzione di callback. L'accumulatore è di nuovo `undefined` e il valore corrente è "4". `undefined` e `4` vengono loggati. +

+
+ +--- + +###### 66. Con quale costruttore possiamo estendere la classe `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Risposta +

+ +#### Risposta: B + +In una classe derivata, non puoi accedere alla chiave `this` prima di chiamare `super`. Se provi a farlo, genererà un ReferenceError: 1 e 4 genererebbero un errore di riferimento. + +Con la chiave `super`, chiamiamo il costruttore di quella classe parent con gli argomenti forniti. Il costruttore del parent riceve l'argomento `name`, quindi passiamo `name` a `super`. + +La classe `Labrador` riceve due argomenti, `name` poiché estende `Dog`, e `size` come proprietà extra sulla classe `Labrador`. Entrambi devono essere passati alla funzione di costruzione su `Labrador`, cosa che viene eseguita correttamente usando il costruttore 2. + +

+
+ +--- + +###### 67. Qual è l'output? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Risposta +

+ +#### Risposta: B + +Con la chiave `import` tutti i moduli importati sono _pre-parsed_. Ciò significa che i moduli importati vengono eseguiti _prima_, il codice nel file che importa il modulo viene eseguito _dopo_. + +Questa è una delle differenze tra `require()` in CommonJS e `import`. Con `require()`, puoi caricare le dipendenze su richiesta mentre il codice è in esecuzione. Se avessimo usato `require` invece di `import`, sulla console avremmo loggato `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Qual è l'output? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Risposta +

+ +#### Risposta: A + +Ogni Simbolo è unico. Lo scopo dell'argomento passato a Symbol è di dargli una descrizione. Il valore del Symbol non dipende dall'argomento passato. Mentre testiamo l'uguaglianza, stiamo creando due simboli completamente nuovi: il primo `Symbol('foo')` e il secondo `Symbol('foo')`. Questi due valori sono unici e non uguali tra loro, `Symbol('foo') === Symbol('foo')` quindi restituisce `false`. + +

+
+ +--- + +###### 69. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Risposta +

+ +#### Risposta: C + +Con il metodo `padStart`, possiamo aggiungere un riempimento all'inizio di una stringa. Il valore passato a questo metodo è la lunghezza _totale_ della stringa insieme al riempimento. La stringa `"Lydia Hallie"` ha una lunghezza di `12`. `name.padStart(13)` inserisce quindi 1 spazio all'inizio della stringa, perché 12 + 1 è 13. + +Se l'argomento passato al metodo `padStart` è inferiore alla lunghezza dell'array, non verrà aggiunto alcun riempimento. + +

+
+ +--- + +###### 70. Qual è l'output? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Una stringa contenente i code points +- D: Errore + +
Risposta +

+ +#### Risposta: A + +Con l'operatore `+` puoi concatenare stringhe. In questo caso, stiamo concatenando la stringa `"🥑"` con la stringa `"💻"`, ottenendo `"🥑💻"`. + +

+
+ +--- + +###### 71. Come possiamo loggare i valori commentati dopo l'istruzione console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're gone here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
Risposta +

+ +#### Risposta: C + +Una funzione generator "mette in pausa" la sua esecuzione quando incontra la parola chiave `yield`. Innanzitutto dobbiamo lasciare che la funzione produca la stringa "Ami JavaScript?", che può essere eseguita chiamando `game.next().value`. + +Ogni riga viene quindi eseguita, finché non trova la prima chiave `yield`. C'è una parola chiave `yield` sulla prima riga all'interno della funzione: l'esecuzione si interrompe con il primo rendimento! _Questo significa che la variabile `answer` non è ancora definita!_ + +Quando chiamiamo `game.next("Yes").value`, il precedente `yield` viene sostituito con il valore dei parametri passati alla funzione `next()`, in questo caso `"Yes"`. Il valore della variabile `answer` è ora uguale a `"Yes"`. La condizione dell'istruzione if restituisce `false` e `JavaScript loves you back ❤️` viene registrato. + +

+
+ +--- + +###### 72. Qual è l'output? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Risposta +

+ +#### Risposta: C + +`String.raw` restituisce una stringa in cui gli escape (`\n`, `\v`, `\t` ecc.) vengono ignorati! I backslash possono essere un problema poiché potresti finire con qualcosa del tipo: + +`` const path = `C:\Documents\Projects\table.html` `` + +Il che risulterebbe in: + +`"C:DocumentsProjects able.html"` + +Con `String.raw`, il compilatore ignorerebbe semplicemente l'escape e stamperebbe: + +`C:\Documents\Projects\table.html` + +In questo caso, è la stringa `Hello\nworld` che viene loggata. + +

+
+ +--- + +###### 73. Qual è l'output? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +Una funzione asincrona restituisce sempre una promise. L'`await` deve ancora attendere che la promise si risolva: una promise in sospeso viene restituita quando chiamiamo `getData()` per impostare `data` uguale ad essa. + +Se volessimo accedere al valore risolto `"I made it"`, potremmo usare il metodo `.then()` su `data`: + +`data.then(res => console.log(res))` + +Questo avrebbe loggato `"I made it!"` + +

+
+ +--- + +###### 74. Qual è l'output? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +Il metodo `.push()` restituisce la _lunghezza_ del nuovo array! +Inizialmente, l'array conteneva un solo elemento (la stringa `"banana"`) e aveva una lunghezza di `1`. Dopo aver aggiunto la stringa `"apple"` allo stesso array, questo contiene due elementi e ha una lunghezza di `2` + +Attraverso la funzione `addToList`, il metodo `push` modifica l'array originale. +Per restituire l'_array_ dalla funzione invece della _lunghezza dell'array_, serve fare un return di `list` dopo aver inserito l'`item`. + +

+
+ +--- + +###### 75. Qual è l'output? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +`Object.freeze` rende impossibile aggiungere, rimuovere o modificare le proprietà di un oggetto (a meno che il valore della proprietà non sia un altro oggetto). + +Quando creiamo la variabile `shape` e la impostiamo come all'oggetto congelato `box`, anche `shape` si riferisce ad un oggetto congelato. +Puoi controllare se un oggetto è congelato usando `Object.isFrozen`. In questo caso, `Object.isFrozen(shape)` restituisce true, poiché la variabile `shape` ha un riferimento a un oggetto congelato. + +Poiché `shape` è congelata, e poiché il valore di `x` non è un oggetto, non possiamo modificare la proprietà `x`. +`x` è ancora uguale a `10` e `{ x: 10, y: 20 }` viene loggato. + +

+
+ +--- + +###### 76. Qual è l'output? + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: C + +Quando spacchettiamo la proprietà `name` dall'oggetto, assegniamo il suo valore `"Lydia"` a una variabile con il nome `myName`. + +Con `{ name: myName }`, diciamo a JavaScript che vogliamo creare una nuova variabile chiamata `myName` con il valore della proprietà `name`. + +Poiché proviamo a loggare `name`, una variabile che non è definita, viene restituito `undefined` nell'assegnazione. Successivamente, il valore di `Lydia` viene memorizzato tramite l'assegnazione di destrutturazione. + +

+
+ +--- + +###### 77. Questa è una funzione pura? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Yes +- B: No + +
Risposta +

+ +#### Risposta: A + +Una funzione pura è una funzione che restituisce _sempre_ lo stesso risultato, se vengono passati gli stessi argomenti. + +La funzione `sum` restituisce sempre lo stesso risultato. Se le passiamo `1` e `2`, restituirà _sempre_ `3` senza effetti collaterali. Se passiamo `5` e `10`, restituirà _sempre_ `15` e così via. Questa è la definizione di funzione pura. + +

+
+ +--- + +###### 78. Qual è l'output? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Risposta +

+ +#### Risposta: C + +La funzione `add` è una funzione _memoizzata_. Con la memorizzazione, possiamo memorizzare nella cache i risultati di una funzione per velocizzarne l'esecuzione. +In questo caso, creiamo un oggetto `cache` che memorizza i valori precedentemente restituiti. + +Se chiamiamo di nuovo la funzione `addFunction` con lo stesso argomento, prima controlla se ha già ottenuto quel valore nella sua cache, in tal caso, verrà restituito il valore della cache, consentendo di risparmiare tempo di esecuzione. Altrimenti, se non è memorizzato nella cache, calcolerà il valore e lo memorizzerà in seguito. + +Chiamiamo la funzione `addFunction` tre volte con lo stesso valore: alla prima chiamata, il valore della funzione quando `num` è uguale a `10` non è ancora memorizzato nella cache. +La condizione dell'istruzione if `num in cache` restituisce `false`, e il blocco else viene eseguito: `Calculated! 20` viene loggato e il valore del risultato viene aggiunto all'oggetto cache. +`cache` ora è uguale a `{ 10: 20 }`. + +La seconda volta, l'oggetto `cache` contiene il valore che viene restituito per `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene loggato. + +La terza volta, passiamo `5 * 2` alla funzione che viene valutata a `10`. L'oggetto `cache` contiene il valore che viene restituito `10`. La condizione dell'istruzione if `num in cache` restituisce `true` e `'From cache! 20'` viene registrato. + +

+
+ +--- + +###### 79. Qual è l'output? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Risposta +

+ +#### Risposta: A + +Con un ciclo _for-in_, possiamo scorrere su proprietà **enumerabili**. In un array, le proprietà enumerabili sono le "chiavi" degli elementi dell'array, che sono in realtà i loro indici. Potresti immaginare un array come: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Dove le chiavi sono le proprietà enumerabili. `0` `1` `2` `3` viene quindi loggato. + +Con un ciclo _for-of_, possiamo iterare su **iterabili**. Un array è un iterabile. Quando iteriamo sull'array, la variabile "item" è uguale all'elemento su cui sta attualmente iterando, `"☕"` `"💻"` `"🍷"` `"🍫"` viene loggato. + +

+
+ +--- + +###### 80. Qual è l'output? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Risposta +

+ +#### Risposta: C + +Gli elementi di un array possono contenere qualsiasi valore. Numeri, stringhe, oggetti, altri array, null, booleani, undefined e altre espressioni come date, funzioni e calcoli. + +L'elemento sarà uguale al valore restituito. `1 + 2` restituirà quindi `3`, `1 * 2` restituirà `2` e `1 / 2` restituirà `0.5`. + +

+
+ +--- + +###### 81. Qual è l'output? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Di default, gli argomenti hanno il valore di `undefined`, a meno che un valore non sia stato passato alla funzione. In questo caso, non abbiamo passato un valore per l'argomento `name`. `name` è uguale a `undefined` che viene loggato. + +In ES6, possiamo sovrascrivere questo valore predefinito `undefined` con dei parametri predefiniti. Per esempio: + +`function sayHi(name = "Lydia") { ... }` + +In questo caso, se non abbiamo passato un valore o se abbiamo passato `undefined`, `name` sarà sempre uguale alla stringa `Lydia` + +

+
+ +--- + +###### 82. Qual è l'output? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` e `"😍"` +- B: `"🥑"` e `"😎"` +- C: `"😍"` e `"😎"` +- D: `"😎"` e `"😎"` + +
Risposta +

+ +#### Risposta: B + +Il valore della parola chiave `this` dipende da dove la usi. In un **metodo**, come il metodo `getStatus`, la parola chiave `this` si riferisce all'_oggetto a cui appartiene il metodo_. Nel nostro caso il metodo appartiene all'oggetto `data`, quindi `this` si riferisce all'oggetto `data`. Quando logghiamo `this.status`, stiamo chiedendo la proprietà `status` sull'oggetto `data` che è `"🥑"`. + +Con il metodo `call` possiamo cambiare l'oggetto a cui fa riferimento la parola chiave `this`. Nelle **funzioni**, la parola chiave `this` si riferisce all'_oggetto a cui appartiene la funzione_. Abbiamo dichiarato la funzione `setTimeout` sull'_oggetto globale_, quindi all'interno della funzione `setTimeout`, la parola chiave `this` si riferisce all'_oggetto globale_. Sull'oggetto globale c'è una variabile chiamata _status_ con il valore di `"😎"`. Quando si fa un console.log di `this.status`, otteniamo `"😎"`. + +

+
+ +--- + +###### 83. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Risposta +

+ +#### Risposta: A + +Impostiamo la variabile `city` uguale al valore della proprietà chiamata `city` sull'oggetto `person`. Non c'è alcuna proprietà su questo oggetto chiamato `city`, quindi la variabile `city` ha il valore di `undefined`. + +Nota che _non_ stiamo facendo riferimento all'oggetto `person`! Impostiamo semplicemente la variabile `city` uguale al valore corrente della proprietà `city` sull'oggetto `person`. + +Quindi, impostiamo `city` uguale alla stringa `"Amsterdam"`. Questo non cambia l'oggetto `person`: non c'è alcun riferimento a quell'oggetto. + +Quando si logga l'oggetto `person`, viene restituito l'oggetto non modificato. + +

+
+ +--- + +###### 84. Qual è l'output? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +Le variabili con la chiave `const` e `let` sono _block-scoped_. Un blocco è qualsiasi cosa si trovi tra parentesi graffe (`{ }`). In questo caso, le parentesi graffe delle istruzioni if/else. Non puoi fare riferimento a una variabile al di fuori del blocco in cui è dichiarata, viene quindi generato un ReferenceError. + +

+
+ +--- + +###### 85. Che tipo di informazioni verrebbero loggate? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Il risultato del metodo `fetch`. +- B: Il risultato della seconda invocazione del metodo `fetch`. +- C: Il risultato della callback nel precedente `.then()`. +- D: Sarebbe sempre undefined. + +
Risposta +

+ +#### Risposta: C + +Il valore di `res` nel secondo `.then` è uguale al valore restituito del precedente `.then`. Puoi continuare a concatenare i `.then` in questo modo, dove il valore viene passato al gestore successivo. + +

+
+ +--- + +###### 86. Quale opzione è un modo per impostare `hasName` uguale a `true`, se non puoi passare `true` come argomento? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Risposta +

+ +#### Risposta: A + +Con `!!name`, determiniamo se il valore di `name` è vero o falso. Se il nome è vero, cosa che vogliamo testare, `!name` restituisce `false`. +`!false` (che è `!!name`) restituisce `true`. + +Impostando `hasName` uguale a `name`, imposti `hasName` uguale a qualsiasi valore passato alla funzione `getName`, non il valore booleano `true`. + +`new Boolean(true)` restituisce un oggetto wrapper, non il valore booleano stesso. + +`name.length` restituisce la lunghezza dell'argomento passato, non se è `true`. + +

+
+ +--- + +###### 87. Qual è l'output? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +Per ottenere un carattere in un indice specifico di una stringa, puoi usare la notazione tra parentesi. Il primo carattere nella stringa ha indice 0 e così via. In questo caso, vogliamo ottenere l'elemento con indice 0, il carattere `"I'`, che viene loggato. + +Tieni presente che questo metodo non è supportato in IE7 e versioni precedenti. In tal caso, usa `.charAt()`. + +

+
+ +--- + +###### 88. Qual è l'output? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +È possibile impostare il valore di un parametro predefinito uguale a un altro parametro della funzione, purché sia stato definito _prima_ del parametro predefinito. Passiamo il valore `10` alla funzione `sum`. Se la funzione `sum` riceve solo 1 argomento, significa che il valore di `num2` non è passato e il valore di `num1` è uguale al valore passato `10` in questo caso. Il valore predefinito di `num2` è il valore di `num1`, che è `10`. `num1 + num2` restituisce `20`. + +Se stai cercando di impostare il valore di un parametro predefinito uguale a un parametro che è definito _dopo_ (a destra), il valore del parametro non è stato ancora inizializzato, il che genererà un errore. +

+
+ +--- + +###### 89. Qual è l'output? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
Risposta +

+ +#### Risposta: A + +Con la sintassi `import * as name`, importiamo _tutte le esportazioni_ dal file `module.js` nel file `index.js` come nuovo oggetto chiamato `data`. Nel file `module.js` ci sono due esportazioni: l'esportazione predefinita e un'esportazione denominata. L'esportazione predefinita è una funzione che restituisce la stringa `"Hello World"`, e l'esportazione denominata è una variabile chiamata `name` che ha il valore della stringa `"Lydia"`. + +L'oggetto `data` ha una proprietà `default` per l'esportazione predefinita, altre proprietà hanno i nomi delle esportazioni e i loro valori corrispondenti. + +

+
+ +--- + +###### 90. Qual è l'output? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Risposta +

+ +#### Risposta: C + +Le classi sono come caramelle sintattiche. L'equivalente della classe `Person` come funzione sarebbe: + +```javascript +function Person() { + this.name = name; +} +``` + +Instanziando un costruttore con `new` si ottiene la creazione di un'istanza di `Person`, la chiave `typeof` restituisce `"object"`. `typeof member` restituisce `"object"`. + +

+
+ +--- + +###### 91. Qual è l'output? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Risposta +

+ +#### Risposta: D + +Il metodo `.push` restituisce la _nuova lunghezza_ dell'array, non l'array stesso! Impostando `newList` uguale a `[1, 2, 3].push(4)`, settiamo `newList` uguale alla nuova lunghezza dell'array: `4`. + +Quindi quando proviamo a usare il metodo `.push` su `newList` poiché `newList` è il valore numerico `4`, non possiamo usare il metodo `.push` e viene generato un TypeError. + +

+
+ +--- + +###### 92. Qual è l'output? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Risposta +

+ +#### Risposta: D + +Le funzioni regolari, come la funzione `giveLydiaPizza`, hanno una proprietà `prototipo`, che è un oggetto (prototype object) con un `costruttore`. Tuttavia, le arrow functions, come la funzione `giveLydiaChocolate`, non hanno una proprietà `prototype`. Viene quindi restituito `undefined` quando si tenta di accedere alla proprietà `prototype` usando `giveLydiaChocolate.prototype`. +

+
+ +--- + +###### 93. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` e `age` `21` +- B: `["name", "Lydia"]` e `["age", 21]` +- C: `["name", "age"]` e `undefined` +- D: `Error` + +
Risposta +

+ +#### Risposta: A + +`Object.entries(person)` restituisce un array di array nidificati, contenente le chiavi e gli oggetti: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Usando il ciclo `for-of`, possiamo scorrere ogni elemento nell'array, i sottoarray in questo caso. Possiamo destrutturare i sottoarray istantaneamente nel ciclo for-of, usando `const [x, y]`. `x` è uguale al primo elemento, `y` è uguale al secondo elemento. + +Il primo sottoarray è `[ "name", "Lydia" ]`, con `x` uguale a `"name"`, e `y` uguale a `"Lydia"`, che vengono loggati. +Il secondo sottoarray è `[ "age", 21 ]`, con `x` uguale a `"age"`, e `y` uguale a `21`, che vengono loggati. + +

+
+ +--- + +###### 94. Qual è l'output? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: D + +`...args` è un parametro rest. Il valore del parametro rest è un array contenente tutti gli argomenti, **e può essere solo l'ultimo parametro**! In questo esempio, il parametro rest è in seconda posizione. Questo non è possibile e genererà un errore di sintassi. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +L'esempio qui sopra invece funziona e restituisce l'array `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Qual è l'output? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` and `b is bigger`, `3` +- B: `a is bigger`, `undefined` and `b is bigger`, `undefined` +- C: `undefined` and `undefined` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +In JavaScript, non _è necessario_ scrivere il punto e virgola (`;`) in modo esplicito poiché il motore JavaScript li aggiunge comunque dopo le istruzioni. +Questo procedimento è chiamato **Automatic Semicolon Insertion**. Un'istruzione può ad esempio essere una variabile o parole chiave come `throw`, `return`, `break`, ecc. + +Qui, abbiamo scritto un'istruzione di `return` e un altro valore `a + b` su una _nuova riga_. Tuttavia, trattandosi di una nuova linea, il motore non sa che in realtà è il valore che volevamo restituire. Invece, ha aggiunto automaticamente un punto e virgola dopo `return`. + +Potresti considerare ad esempio: + +```javascript +return; +a + b; +``` + +`a + b` non viene mai raggiunto, poiché la funzione smette di funzionare dopo la parola chiave `return`. +Se non viene restituito alcun valore, come qui, la funzione restituisce `undefined`. Nota: non c'è un inserimento automatico dopo le istruzioni `if/else`! + +

+
+ +--- + +###### 96. Qual è l'output? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +Possiamo impostare classi uguali ad altre classi/costruttori di funzioni. In questo caso, impostiamo `Person` uguale a `AnotherPerson`. Il name su questo costruttore è `Sarah`, quindi la proprietà del nome di`Person` sulla nuova istanza `member` è `"Sarah"`. + +

+
+ +--- + +###### 97. Qual è l'output? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` e `["{Symbol('a')"]` +- B: `{}` e `[]` +- C: `{ a: "b" }` e `["a"]` +- D: `{Symbol('a'): 'b'}` e `[]` + +
Risposta +

+ +#### Risposta: D + +Un simbolo non è _enumerabile_. Il metodo Object.keys restituisce tutte le proprietà _enumerabili_ su un oggetto. Il simbolo non sarà visibile e verrà restituito un array vuoto. Quando si logga l'intero oggetto, tutte le proprietà saranno visibili, anche quelle non enumerabili. + +Questa è una delle tante qualità di un simbolo: oltre a rappresentare un valore del tutto univoco (che evita collisioni accidentali di nomi sugli oggetti, ad esempio quando si lavora con 2 librerie che vogliono aggiungere proprietà allo stesso oggetto), puoi anche "nascondere" proprietà sugli oggetti in questo modo (anche se non del tutto. Puoi comunque accedere ai simboli usando il metodo `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Qual è l'output? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` e `SyntaxError` +- B: `[1, [2, 3, 4]]` e `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` e `{ name: "Lydia", age: 21 }` +- D: `Error` e `{ name: "Lydia", age: 21 }` + +
Risposta +

+ +#### Risposta: A + +La funzione `getList` riceve un array come argomento. Tra le parentesi della funzione `getList`, destrutturiamo subito questo array. Esempio: + +`[x, ...y] = [1, 2, 3, 4]` + +Con il parametro rest `...y`, mettiamo tutti gli argomenti "rimanenti" in un array. Gli argomenti rimanenti sono `2`, `3` e `4` in questo caso. +Il valore di `y` è un array, contenente tutti i parametri rimanenti. Il valore di `x` è uguale a `1` in questo caso, quindi quando facciamo un console.log di `[x, y]`, viene loggato `[1, [2, 3, 4]]`. + +La funzione `getUser` riceve un oggetto. Con le arrow functions, non _è necessario_ scrivere parentesi graffe se restituiamo solo un valore. Tuttavia, se vuoi restituire istantaneamente un _oggetto_ da una arrow function, devi scriverlo tra parentesi tonde, altrimenti tutto ciò che si trova tra le due parentesi graffe verrà interpretato come un'istruzione di blocco. In questo caso il codice tra parentesi non è un codice JavaScript valido, quindi viene generato un `SyntaxError`. + +La seguente funzione avrebbe restituito un oggetto: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Qual è l'output? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: C + +La variabile `name` contiene il valore di una stringa, che non è una funzione, quindi non può essere invocata. + +I TypeErrors vengono generati quando un valore non è del tipo previsto. JavaScript "prevede" che `name` è una funzione poiché stiamo cercando di invocarla. In realtà è una stringa, quindi viene generato un TypeError: name is not a function! + +I SyntaxErrors vengono generati quando si scrive qualcosa che non è valido in JavaScript, ad esempio quando si scrive la parola `return` come `rerun`. +I ReferenceErrors vengono generati quando JavaScript non è in grado di trovare un riferimento a un valore a cui stai tentando di accedere. + +

+
+ +--- + +###### 100. Qual è il valore dell'output? + +```javascript +// 🎉✨ This is my 100th question! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Risposta +

+ +#### Risposta: B + +`[]` è un valore vero. Con l'operatore `&&`, verrà restituito il valore di destra se il valore di sinistra è un valore reale. In questo caso, il valore di sinistra `[]` è un valore vero, quindi `"Im'` viene restituito. + +`""` è un valore falso. Se il valore di sinistra è falso, non viene restituito nulla. `n't` quindi non viene restituito. + +

+
+ +--- + +###### 101. Qual è il valore dell'output? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Risposta +

+ +#### Risposta: C + +Con l'operatore `||` possiamo restituire il primo operando veritiero. Se tutti i valori sono falsi, viene restituito l'ultimo operando. + +`(false || {} || null)`: l'oggetto vuoto `{}` è un valore veritiero. Questo è il primo (e unico) valore veritiero, che viene restituito. `one` è uguale a `{}`. + +`(null || false || "")`: tutti gli operandi sono valori falsi. Ciò significa che viene restituito l'ultimo operando, `""`. `two` è uguale a `""`. + +`([] || 0 || "")`: l'array vuoto`[]` è un valore veritiero. Questo è il primo valore veritiero, che viene restituito. `three` è uguale a `[]`. + +

+
+ +--- + +###### 102. Qual è il valore dell'output? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` e `I have resolved!`, `second` +- B: `second`, `I have resolved!` e `second`, `I have resolved!` +- C: `I have resolved!`, `second` e `second`, `I have resolved!` +- D: `second`, `I have resolved!` e `I have resolved!`, `second` + +
Risposta +

+ +#### Risposta: D + +Con una promise, in pratica diciamo _Voglio eseguire questa funzione, ma per ora la metto da parte mentre è in esecuzione poiché ciò potrebbe richiedere del tempo. Solo quando un determinato valore viene risolto (o rifiutato) e quando lo stack di chiamate è vuoto, voglio utilizzare questo valore._ + +Possiamo ottenere questo valore sia con `.then` che con la chiave `await` in una funzione `async`. Sebbene possiamo ottenere il valore di una promise sia con `.then` che con `await`, funzionano in modo leggermente diverso. + +Nella `first Function`, abbiamo (più o meno) messo da parte la funzione myPromise mentre era in esecuzione, ma abbiamo continuato a eseguire l'altro codice, che in questo caso è `console.log('second')`. Quindi, la funzione è stata risolta con la stringa `I have resolved`, che è stata quindi loggata dopo aver visto che lo stack di chiamate era vuoto. + +Con await in `secondFunction`, mettiamo letteralmente in pausa l'esecuzione di una funzione asincrona fino a quando il valore non è stato risolto prima di passare alla riga successiva. + +Ciò significa che ha aspettato che `myPromise` si risolvesse con il valore `I have resolved`, e solo allora, siamo passati alla riga successiva e `second` è stato loggato. + +

+
+ +--- + +###### 103. Qual è il valore dell'output? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Risposta +

+ +#### Risposta: C + +L'operatore `+` non viene utilizzato solo per aggiungere valori numerici, ma possiamo anche usarlo per concatenare stringhe. Ogni volta che il motore JavaScript vede che uno o più valori non sono un numero, forza il numero in una stringa. + +Il primo è `1`, che è un valore numerico. `1 + 2` restituisce il numero 3. + +Tuttavia, la seconda è una stringa `"Lydia"`. `"Lydia"` è una stringa e `2` è un numero: `2` viene forzato in una stringa. `"Lydia"` e `"2"` vengono concatenati, il che risulta nella stringa `"Lydia2"`. + +`{ name: "Lydia" }` è un oggetto. Né un numero né un oggetto sono una stringa, quindi li rende stringhe entrambi. Ogni volta che stringhiamo un oggetto regolare, diventa `"[object Object]"`. `"[object Object]"` concatenato con `2` diventa `"[object Object]"`. + +

+
+ +--- + +###### 104. Qual è il suo valore? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Risposta +

+ +#### Risposta: C + +Possiamo passare a `Promise.resolve` qualsiasi tipo di valore desideriamo, sia una promise che una non-promise. Il metodo stesso restituisce una promise con il valore risolto (``). Se si passa una funzione regolare, sarà una promise risolta con un valore regolare. Se mandi una promise, sarà una promise risolta con il valore risolto di quella promise passata. + +In questo caso, abbiamo appena passato il valore numerico `5`. Restituisce una promise risolta con il valore `5`. + +

+
+ +--- + +###### 105. Qual è il suo valore? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: B + +Gli oggetti vengono passati per riferimento. Quando controlliamo gli oggetti per strict equality (`===`), stiamo confrontando i loro riferimenti. + +Abbiamo impostato il valore predefinito per `person2` uguale all'oggetto `person` e abbiamo passato l'oggetto `person` come valore per `person1`. + +Ciò significa che entrambi i valori hanno un riferimento allo stesso punto in memoria, quindi sono uguali. + +Il blocco di codice nell'istruzione `else` viene eseguito e `They are the same!` viene loggato. + +

+
+ +--- + +###### 106. Qual è il suo valore? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: D + +In JavaScript, abbiamo due modi per accedere alle proprietà di un oggetto: le bracket notation o le dot notation. In questo esempio, utilizziamo la notazione con il punto (`colorConfig.colors`) invece della notazione tra parentesi (`colorConfig["colors"]`). + +Con la notazione del punto, JavaScript tenta di trovare la proprietà sull'oggetto con quel nome esatto. In questo esempio, JavaScript tenta di trovare una proprietà chiamata `colors` sull'oggetto `colorConfig`. Non esiste una proprietà chiamata `colors`, quindi restituisce `undefined`. Quando proviamo ad accedere al valore del primo elemento usando `[1]`, non possiamo farlo su un valore che è `undefined`, quindi genera un `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript interpreta (o decomprime) le istruzioni. Quando usiamo la notazione tra parentesi, vede la prima parentesi aperta `[` e continua finché non trova la parentesi chiusa `]`. Solo allora valuterà la dichiarazione. Se avessimo usato `colorConfig[colors[1]]`, avrebbe restituito il valore della proprietà `red` sull'oggetto `colorConfig`. + +

+
+ +--- + +###### 107. Qual è il suo valore? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Risposta +

+ +#### Risposta: A + +Le emoji sono unicode. L'unicode per l'emoji del cuore è `"U+2764 U+FE0F"`. Questi sono sempre gli stessi per gli stessi emoji, stiamo confrontando due stringhe uguali tra loro, e quindi restituisce true. + +

+
+ +--- + +###### 108. Quale di questi metodi modifica l'array originale? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Risposta +

+ +#### Risposta: D + +Con il metodo `splice` modifichiamo l'array originale cancellando, sostituendo o aggiungendo elementi. In questo caso, abbiamo rimosso 2 elementi dall'indice 1 (abbiamo rimosso `'🥑'` e `'😍'`) e aggiunto invece l'emoji ✨. + +`map`, `filter` e `slice` restituiscono un nuovo array, `find` restituisce un elemento e `reduce` restituisce un valore ridotto. +

+
+ +--- + +###### 109. Qual è l'output? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale alla stringa con l'emoji della pizza, `'🍕'`. Una stringa è un tipo di dati primitivo. In JavaScript, i tipi di dati primitivi non interagiscono per riferimento. + +In JavaScript, i tipi di dati primitivi (tutto ciò che non è un oggetto) interagiscono per _value_. In questo caso, impostiamo il valore della proprietà `favoriteFood` sull'oggetto `info` uguale al valore del primo elemento nell'array `food`, in questo caso la stringa con l'emoji della pizza (`'🍕'`). Una stringa è un tipo di dati primitivo e interagisce per valore (vedi il mio [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) se sei interessato a saperne di più). + +Quindi, cambiamo il valore della proprietà `favoriteFood` sull'oggetto `info`. L'array `food` non è cambiato, poiché il valore di `favoriteFood` era semplicemente una _copia_ del valore del primo elemento nell'array e non ha un riferimento allo stesso punto in memoria dell'elemento su ` food[0]`. Quando logghiamo food, è ancora l'array originale, `['🍕', '🍫', '🥑', '🍔']`. +

+
+ +--- + +###### 110. Cosa fa questo metodo? + +```javascript +JSON.parse(); +``` + +- A: converte JSON in un valore JavaScript +- B: converte un oggetto JavaScript in JSON +- C: converte qualsiasi valore JavaScript in JSON +- D: converte JSON in un oggetto solo JavaScript + +
Risposta +

+ +#### Risposta: A + +Con il metodo `JSON.parse()`, possiamo analizzare la stringa JSON come un valore JavaScript. + +```javascript +// Stringhiamo un numero in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Stringhiamo un array in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Stringhiamo un object in un JSON valido, quindi analizziamo la stringa JSON come valore JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Qual è l'output? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: D + +Ogni funzione ha il proprio _contesto di esecuzione_ (o _ambito_). La funzione `getName` cerca prima all'interno del proprio contesto (scope) per vedere se contiene la variabile `name` a cui stiamo cercando di accedere. In questo caso, la funzione `getName` contiene la propria variabile `name` perché dichiariamo la variabile `name` con la chiave `let`, e con il valore di `'Sarah'`. + +Le variabili con la chiave `let` (e `const`) vengono sollevate, ma a differenza di `var`, non vengono inizializzate. Non sono quindi accessibili prima della riga in cui le dichiariamo (inizializziamo). Questa è chiamata "temporal dead zone". Quando proviamo ad accedere alle variabili prima che vengano dichiarate, JavaScript genera un `ReferenceError`. + +Se non avessimo dichiarato la variabile `name` all'interno della funzione `getName`, JavaScript avrebbe esaminato la _scope chain_. Lo scope esterno ha una variabile chiamata `name` con il valore di `Lydia`. In tal caso, avrebbe loggato "Lydia". + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Qual è l'output? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` e `a` +- B: `a` e `undefined` +- C: `['a', 'b', 'c']` e `a` +- D: `a` e `['a', 'b', 'c']` + +
Risposta +

+ +#### Risposta: C + +Con la parola chiave `yield`, otteniamo valori in una funzione generatore. Con la chiave `yield*`, possiamo produrre valori da un'altra funzione del generatore, o da un oggetto iterabile (per esempio un array). + +In `generatorOne`, produciamo l'intero array `['a', 'b', 'c']` usando la parola chiave `yield`. Il valore della proprietà `value` sull'oggetto restituito dal metodo `next` su `one` (`one.next().value`) è uguale all'intero array `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +In `generatorTwo`, utilizziamo la parola chiave `yield*`. Ciò significa che il primo valore ottenuto è `two`, ed è uguale al primo valore ottenuto nell'iteratore. L'iteratore è l'array `['a', 'b', 'c']`. Il primo valore ottenuto è `a`, quindi la prima volta che chiamiamo `two.next().value`, viene restituito `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Qual è l'output? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Risposta +

+ +#### Risposta: A + +Le espressioni all'interno dei template literals vengono valutate per prime. Ciò significa che la stringa conterrà il valore restituito dell'espressione, in questo caso la funzione immediatamente invocata `(x => x)('I love')`. Passiamo il valore `'I love'` come argomento alla funzione freccia `x => x`. `x` è uguale a `'I love'`, che viene restituito. Ciò si traduce in `I love to program`. + +

+
+ +--- + +###### 114. Cosa accadrà? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: La callback `setInterval` non verrà invocata +- B: La callback `setInterval` viene invocata una volta +- C: La callback `setInterval` verrà comunque chiamata ogni secondo +- D: Non abbiamo mai invocato `config.alert()`, config è `null` + +
Risposta +

+ +#### Risposta: C + +Normalmente quando impostiamo oggetti uguali a `null`, quegli oggetti vengono _garbage collected_ poiché non c'è più alcun riferimento a quell'oggetto. Tuttavia, poiché la funzione di callback all'interno di `setInterval` è una funzione freccia (quindi legata all'oggetto `config`), la funzione di callback mantiene ancora un riferimento all'oggetto `config`. +Finché c'è un riferimento, l'oggetto non verrà raccolto. +Poiché si tratta di un intervallo, impostare `config` su `null` o `delete`-ing `config.alert` non raccoglierà l'intervallo, quindi l'intervallo verrà comunque chiamato. +Dovrebbe essere cancellato con `clearInterval(config.alert)` per rimuoverlo dalla memoria. +Dal momento che non è stato cancellato, la funzione di callback `setInterval` verrà comunque invocata ogni 1000 ms (1 s). + +

+
+ +--- + +###### 115. Quali metodi restituiranno il valore `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 e 3 +- D: Tutti + +
Risposta +

+ +#### Risposta: B + +Quando si aggiunge una coppia chiave/valore usando il metodo `set`, la chiave sarà il valore del primo argomento passato alla funzione `set`, e il valore sarà il secondo argomento. La chiave è _function_ `() => 'greeting'` in questo caso, e il valore `'Hello world'`. `myMap` ora è `{ () => 'greeting' => 'Hello world!' }`. + +1 è sbagliato, poiché la chiave non è `'greeting'` ma `() => 'greeting'`. +3 è sbagliato, poiché stiamo creando una nuova funzione passandola come parametro al metodo `get`. L'oggetto interagisce per _reference_. Le funzioni sono oggetti, che è il motivo per cui due funzioni non sono mai rigorosamente uguali, anche se identiche: hanno un riferimento a un punto diverso della memoria. + +

+
+ +--- + +###### 116. Qual è l'output? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Risposta +

+ +#### Risposta: C + +Entrambe le funzioni `changeAge` e `changeAgeAndName` hanno un parametro predefinito, ovvero un oggetto _appena_ creato `{ ...person }`. Questo oggetto ha copie di tutte le chiavi/valori nell'oggetto `person`. + +Per prima cosa, invochiamo la funzione `changeAge` e passiamo l'oggetto `person` come argomento. Questa funzione aumenta il valore della proprietà `age` di 1. `person` ora è `{ name: "Lydia", age: 22 }`. + +Quindi, invochiamo la funzione `changeAgeAndName`, tuttavia non passiamo un parametro. Invece, il valore di `x` è uguale a un _nuovo_ oggetto: `{ ...person }`. Poiché si tratta di un nuovo oggetto, non influisce sui valori delle proprietà sull'oggetto `person`. `person` è ancora uguale a `{ name: "Lydia", age: 22 }`. +

+
+ +--- + +###### 117. Quale delle seguenti opzioni restituirà `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Risposta +

+ +#### Risposta: C + +Con l'operatore spread `...`, possiamo _distribuire_ gli iterabili come singoli elementi. La funzione `sumValues` riceve tre argomenti: `x`, `y` e `z`. `...[1, 2, 3]` risulterà in `1, 2, 3`, che passiamo alla funzione `sumValues`. + +

+
+ +--- + +###### 118. Qual è l'output? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con l'operando `+=`, stiamo incrementando il valore di `num` di `1`. `num` aveva il valore iniziale `1`, quindi `1 + 1` è `2`. L'elemento sul secondo indice nell'array `list` è 🥰, `console.log(list[2])` stampa 🥰. + +

+
+ +--- + +###### 119. Qual è l'output? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Con l'operatore di concatenamento opzionale `?.`, non è più necessario verificare esplicitamente se i valori annidati più profondi sono validi o meno. Se stiamo cercando di accedere a una proprietà su un valore `undefined` o `null` (_nullish_), l'espressione va in cortocircuito e restituisce `undefined`. + +`person.pet?.name`: `person` ha una proprietà denominata `pet`: `person.pet` non è nullo. Ha una proprietà chiamata `name` e restituisce `Mara`. +`person.pet?.family?.name`: `person` ha una proprietà denominata `pet`: `person.pet` non è nullo. `pet` _non_ ha una proprietà chiamata `family`, `person.pet.family` è nullo. L'espressione restituisce `undefined`. +`person.getFullName?.()`: `person` ha una proprietà denominata `getFullName`: `person.getFullName()` non è nullo e può essere invocato, il che restituisce `Lydia Hallie`. +`member.getLastName?.()`: la variabile `member` non esiste quindi viene generato un `ReferenceError`! + +

+
+ +--- + +###### 120. Qual è l'output? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Risposta +

+ +#### Risposta: B + +Abbiamo passato la condizione `groceries.indexOf("banana")` all'istruzione if. `groceries.indexOf("banana")` restituisce `0`, che è un valore falso. Poiché la condizione nell'istruzione if è falsa, il codice nel blocco `else` viene eseguito e `We don't have to buy bananas!` viene registrato. + +

+
+ +--- + +###### 121. Qual è l'output? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Risposta +

+ +#### Risposta: D + +Il metodo `language` è un `setter`. I setter non detengono un valore effettivo, il loro scopo è _modificare_ le proprietà. Quando si chiama un metodo `setter`, viene restituito `undefined`. + +

+
+ +--- + +###### 122. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Risposta +

+ +#### Risposta: C + +`typeof name` restituisce `"string"`. La stringa `"string"` è un valore veritiero, quindi `!typeof name` restituisce il valore booleano `false`. `false === "object"` e `false === "string"` restituiscono entrambi `false`. + +(Se volessimo verificare se il tipo era (non)uguale a un certo tipo, avremmo dovuto scrivere `!==` invece di `!typeof`) +

+
+ +--- + +###### 123. Qual è l'output? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Risposta +

+ +#### Risposta: A + +La funzione `add` restituisce una arrow function, che restituisce una arrow function, che restituisce arrow function (mi segui ancora?). +La prima funzione riceve un argomento `x` con il valore di `4`. Invochiamo la seconda funzione, che riceve un argomento `y` con il valore `5`. Quindi invochiamo la terza funzione, che riceve un argomento `z` con il valore `6`. Quando si tenta di accedere ai valori `x`, `y` e `z` all'interno dell'ultima arrow function, il motore JS risale la catena dell'ambito per trovare i valori per `x` e `y`. Questo restituisce `4` `5` `6`. + +

+
+ +--- + +###### 124. Qual è l'output? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: C + +La funzione `range` restituisce un oggetto asincrono con promises per ogni elemento nell'intervallo che passiamo: `Promise{1}`, `Promise{2}`, `Promise{3}`. Impostiamo la variabile `gen` uguale all'oggetto asincrono, dopodiché lo eseguiamo in loop usando un ciclo `for await ... of`. Impostiamo la variabile `item` uguale ai valori Promise restituiti: prima `Promise{1}`, poi `Promise{2}`, quindi `Promise{3}`. Poiché stiamo _attendendo_ il valore di `item`, la promise risolta, vengono restituiti i _valori_ risolti delle promises: `1`, `2` e quindi `3`. + +

+
+ +--- + +###### 125. Qual è l'output? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Risposta +

+ +#### Risposta: D + +`myFunc` si aspetta un oggetto con le proprietà `x`, `y` e `z` come argomento. Poiché stiamo passando solo tre valori numerici separati (1, 2, 3) invece di un oggetto con le proprietà `x`, `y` e `z` ({x: 1, y: 2, z: 3}), `x`, `y` e `z` hanno il loro valore predefinito di `undefined`. + +

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

+ +#### Risposta: B + +Con il metodo `Intl.NumberFormat`, possiamo formattare i valori numerici in qualsiasi locale. Formattiamo il valore numerico `130` nella locale `en-US` come `unit` in `mile-per-hour`, che risulta in `130 mph`. Il valore numerico `300` nella locale `en-US` come `currency` in `USD` risulta in `$300.00`. + +

+
+ +--- + +###### 127. Qual è l'output? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Risposta +

+ +#### Risposta: B + +Destrutturando gli oggetti, possiamo decomprimere i valori dall'oggetto di destra e assegnare il valore decompresso al valore dello stesso nome di proprietà sull'oggetto di sinistra. In questo caso, stiamo assegnando il valore "💀" a `spookyItems[3]`. Ciò significa che stiamo modificando l'array `spookyItems`, stiamo aggiungendo il "💀" ad esso. Quando facciamo console.log di `spookyItems`, `["👻", "🎃", "🕸", "💀"]` viene loggato. + +

+
+ +--- + +###### 128. Qual è l'output? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Risposta +

+ +#### Risposta: C + +Con il metodo `Number.isNaN`, puoi controllare se il valore passato è un _valore numerico_ e uguale a `NaN`. `name` non è un valore numerico, quindi `Number.isNaN(name)` restituisce `false`. `age` è un valore numerico, ma non è uguale a `NaN`, quindi `Numero.isNaN(age)` restituisce `false`. + +Con il metodo `isNaN`, puoi verificare se il valore che passi non è un numero. `name` non è un numero, quindi `isNaN(name)` restituisce true. `age` è un numero, quindi `isNaN(age)` restituisce `false`. +

+
+ +--- + +###### 129. Qual è l'output? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: D + +Le variabili dichiarate con la chiave `const` non sono referenziabili prima della loro inizializzazione: questa viene chiamata _temporal dead zone_. Nella funzione `getInfo`, la variabile `randomValue` ha lo scopo nell'ambito funzionale di `getInfo`. Nella riga in cui vogliamo registrare il valore di `typeof randomValue`, la variabile `randomValue` non è ancora inizializzata: viene lanciato un `ReferenceError`! Il motore non è andato giù per la catena dell'ambito poiché abbiamo dichiarato la variabile `randomValue` nella funzione `getInfo`. +

+
+ +--- + +###### 130. Qual è l'output? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Risposta +

+ +#### Risposta: C + +Nel blocco `try`, stiamo loggando il valore atteso della variabile `myPromise`: `"Woah some cool data"`. Poiché non sono stati generati errori nel blocco `try`, il codice nel blocco `catch` non viene eseguito. Il codice nel blocco `finally` viene eseguito _sempre_, `"Oh finally!"` viene loggato. + +

+
+ +--- + +###### 131. Qual è l'output? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Risposta +

+ +#### Risposta: B + +Con il metodo `flat`, possiamo creare un nuovo array appiattito. La profondità dell'array appiattito dipende dal valore che passiamo. In questo caso, abbiamo passato il valore `1` (cosa che non dovevamo fare, questo è il valore predefinito), il che significa che solo gli array sulla prima profondità verranno concatenati. `['🥑']` e `['✨', '✨', ['🍕', '🍕']]` in questo caso. Concatenando questi due array si ottengono `['🥑', '✨', '✨', ['🍕', '🍕']]`. +

+
+ +--- + +###### 132. Qual è l'output? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Risposta +

+ +#### Risposta: D + +`counterOne` è un'istanza della classe `Counter`. La classe counter contiene una proprietà `count` sul suo costruttore e un metodo `increment`. Per prima cosa, abbiamo invocato il metodo `increment` due volte chiamando `counterOne.increment()`. Attualmente, `counterOne.count` è `2`. + + + +Quindi, creiamo una nuova variabile `counterTwo` e la impostiamo uguale a `counterOne`. Poiché gli oggetti interagiscono per riferimento, stiamo semplicemente creando un nuovo riferimento allo stesso punto della memoria a cui punta `counterOne`. Poiché ha lo stesso punto in memoria, qualsiasi modifica apportata all'oggetto a cui fa riferimento `counterTwo`, si applica anche a `counterOne`. Attualmente, `counterTwo.count` è `2`. + +Invochiamo `counterTwo.increment()`, che imposta `count` su `3`. Quindi, logghiamo il conteggio su `counterOne`, che stampa `3`. + + + +

+
+ +--- + +###### 133. Qual è l'output? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Risposta +

+ +#### Risposta: C + +Innanzitutto, invochiamo `funcOne`. Sulla prima riga di `funcOne`, chiamiamo la funzione _asincrona_ `setTimeout`, da cui la callback viene inviato all'API Web. (vedi l'articolo sul ciclo degli eventi [qui](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif)) + +Quindi chiamiamo la promise `myPromise`, che è un'operazione _asincrona_. + +Sia la promise che il timeout sono operazioni asincrone, la funzione continua a funzionare mentre è impegnata a completare la promise e a gestire la callback `setTimeout`. Ciò significa che `Last line 1!` viene registrato per primo, poiché questa non è un'operazione asincrona. + +Poiché la callstack non è ancora vuota, la funzione `setTimeout` e la promise in `funcOne` non possono ancora essere aggiunte al callstack. + +In `funcTwo`, la variabile `res` ottiene `Promise` perché `Promise.resolve(Promise.resolve('Promise'))` è equivalente a `Promise.resolve('Promise')` poiché risolvere una promise risolve il suo valore. L'"attesa" in questa riga interrompe l'esecuzione della funzione fino a quando non riceve la risoluzione della promise e quindi continua a funzionare in modo sincrono fino al completamento, quindi `Promise 2!` e poi `Last line 2!` vengono registrati e `setTimeout` viene inviato all'API Web. + +Quindi lo stack di chiamate è vuoto. Le promise sono _microattività_, quindi vengono risolte per prime quando lo stack di chiamate è vuoto, quindi `Promise 1!` viene registrato. + +Ora, da quando `funcTwo` è uscito dallo stack delle chiamate, lo stack delle chiamate è vuoto. Le callback in attesa nella coda (`() => console.log("Timeout 1!")` da `funcOne`, e `() => console.log("Timeout 2!")` da `funcTwo`) vengono aggiunti allo stack di chiamate uno per uno. Il primo callback registra `Timeout 1!` e viene eliminato dallo stack. Quindi, il secondo callback registra `Timeout 2!` e viene eliminato dallo stack. +

+
+ +--- + +###### 134. Come possiamo invocare `sum` in `sum.js` da `index.js?` + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: I valori predefiniti non vengono importati con `*`, solo esportazioni nominali + +
Risposta +

+ +#### Risposta: C + +Con l'asterisco `*`, importiamo tutti i valori esportati da quel file, sia predefinito che nominale. Se avessimo il seguente file: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +Verrebbe loggato quanto segue: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Per l'esempio `sum`, significa che il valore importato `sum` è simile a quanto segue: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Possiamo invocare questa funzione, chiamando `sum.default` + +

+
+ +--- + +###### 135. Qual è l'output? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nulla viene loggato + +
Risposta +

+ +#### Risposta: C + +Con un oggetto Proxy, possiamo aggiungere un comportamento personalizzato a un oggetto che gli passiamo come secondo argomento. In questo caso, passiamo all'oggetto `handler` che conteneva due proprietà: `set` e `get`. `set` viene invocato ogni volta che _settiamo_ valori di proprietà, `get` viene invocato ogni volta che _otteniamo_ (accediamo) valori di proprietà. + +Il primo argomento è un oggetto vuoto `{}`, che è il valore di `person`. A questo oggetto viene aggiunto il comportamento personalizzato specificato nell'oggetto `handler`. Se aggiungiamo una proprietà all'oggetto `person`, `set` verrà invocato. Se accediamo a una proprietà sull'oggetto `person`, `get` viene invocato. + +Innanzitutto, abbiamo aggiunto una nuova proprietà `name` all'oggetto proxy (`person.name = "Lydia"`). `set` viene invocato e registra `"Added a new property!"`. + +Quindi, accediamo a un valore di proprietà sull'oggetto proxy, la proprietà `get` sull'oggetto handler è stata invocata. `"Accessed a property!"` viene registrato. + +

+
+ +--- + +###### 136. Quale delle seguenti opzioni modificherà l'oggetto `persona`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Risposta +

+ +#### Risposta: A + +Con `Object.seal` possiamo impedire che nuove proprietà vengano _aggiunte_ o che proprietà esistenti vengano _rimosse_. + +Tuttavia, puoi comunque modificare il valore delle proprietà esistenti. + +

+
+ +--- + +###### 137. Quale delle seguenti opzioni modificherà l'oggetto `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Risposta +

+ +#### Risposta: C + +Il metodo `Object.freeze` _congela_ un oggetto. Nessuna proprietà può essere aggiunta, modificata o rimossa. + +Tuttavia, blocca solo _poco profondamente_ l'oggetto, il che significa che solo le proprietà _direct_ sull'oggetto sono bloccate. Se la proprietà è un altro oggetto, come `address` in questo caso, le proprietà su quell'oggetto non vengono bloccate e possono essere modificate. + +

+
+ +--- + +###### 138. Qual è l'output? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Risposta +

+ +#### Risposta: A + +Per prima cosa, abbiamo invocato `myFunc()` senza passare alcun argomento. Dal momento che non abbiamo passato argomenti, `num` e `value` hanno i loro valori predefiniti: num è `2` e `value` il valore restituito dalla funzione `add`. Alla funzione `add`, passiamo `num` come argomento, che aveva il valore di `2`. `add` restituisce `4`, che è il valore di `value`. + +Quindi, abbiamo invocato `myFunc(3)` e passato il valore `3` come valore per l'argomento `num`. Non abbiamo passato un argomento per `value`. +Poiché non abbiamo passato un valore per l'argomento `value`, ha ottenuto il valore predefinito: il valore restituito dalla funzione `add`. Ad `add` passiamo `num`, che ha il valore di `3`. `add` restituisce `6`, che è il valore di `value`. + +

+
+ +--- + +###### 139. Qual è l'output? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Risposta +

+ +#### Risposta: D + +In ES2020, possiamo aggiungere variabili private nelle classi usando `#`. Non possiamo accedere a queste variabili al di fuori della classe. Quando proviamo a registrare `counter.#number`, viene generato un SyntaxError: non possiamo accedervi al di fuori della classe `Counter`! + +

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

+ +#### Risposta: B + +Per scorrere i `members` in ogni elemento dell'array `teams`, dobbiamo passare `teams[i].members` alla funzione `getMembers`. La funzione restituisce un oggetto. Per scorrere ogni elemento in questo oggetto generatore, dobbiamo usare `yield*`. + +Se avessimo scritto `yield`, `return yield` o `return`, l'intera funzione del generatore sarebbe stata restituita la prima volta che abbiamo chiamato il metodo `next`. + +

+
+ +--- + +###### 141. Qual è l'output? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Risposta +

+ +#### Risposta: C + +La funzione `addHobby` riceve due argomenti, `hobby` e `hobby` con il valore predefinito dell'array `hobbies` sull'oggetto `person`. + +Per prima cosa, invochiamo la funzione `addHobby` e passiamo `"running"` come valore per `hobby` e un array vuoto come valore per `hobby`. Poiché passiamo un array vuoto come valore per `hobby`, `"running"` viene aggiunto a questo array vuoto. + +Quindi, invochiamo la funzione `addHobby` e passiamo a `"dancing"` come valore per `hobby`. Non abbiamo passato un valore per `hobbies`, quindi ottiene il valore predefinito, la proprietà `hobbies` sull'oggetto `person`. Spostiamo l'hobby `dancing` nell'array `person.hobbies`. + +Infine, invochiamo la funzione `addHobby` e passiamo `"baking"` come valore per `hobby`, e l'array `person.hobbies` come valore per `hobby`. Spostiamo l'hobby `baking` nell'array `person.hobbies`. + +Dopo aver fatto un push di `dancing` e `baking`, il valore di `person.hobbies` è `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Qual è l'output? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Niente, non abbiamo chiamato alcun metodo + +
Risposta +

+ +#### Risposta: B + +Creiamo la variabile `pet` che è un'istanza della classe `Flamingo`. Quando istanziamo questa istanza, il `constructor` su `Flamingo` viene chiamato. Per prima cosa, `"I'm pink. 🌸"` viene loggato, dopodiché chiamiamo `super()`. + +`super()` chiama il costruttore della classe genitore, `Bird`. Il costruttore in `Bird` viene chiamato e registra `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Quale delle opzioni genera un errore? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
Risposta +

+ +#### Risposta: D + +La chiave `const` significa che non possiamo _ridichiarare_ il valore di quella variabile, è di _sola lettura_. Tuttavia, il valore stesso non è immutabile. Le proprietà dell'array `emojis` possono essere modificate, ad esempio facendo un push di nuovi valori, collegandoli o impostando la lunghezza dell'array su 0. + +

+
+ +--- + +###### 144. Cosa dobbiamo aggiungere all'oggetto `person` per ottenere `["Lydia Hallie", 21]` come output di `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Nulla, gli oggetti sono iterabili di default +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Risposta +

+ +#### Risposta: C + +Gli oggetti non sono iterabili per impostazione predefinita. Un iterabile è un iterabile se è presente il protocollo iteratore. +Possiamo aggiungerlo manualmente aggiungendo il simbolo dell'iteratore `[Symbol.iterator]`, che deve restituire un oggetto generatore, ad esempio trasformandolo in una funzione del generatore `*[Symbol.iterator]() {}`. Questa funzione di generazione deve fornire gli `Object.values` dell'oggetto `person` se vogliamo che restituisca l'array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Qual è l'output? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Risposta +

+ +#### Risposta: C + +La condizione `if` all'interno del ciclo `forEach` controlla se il valore di `num` è veritiero o falso. Poiché il primo numero nell'array `nums` è `0`, ovvero un valore falso, il blocco di codice dell'istruzione `if` non verrà eseguito. `count` viene incrementato solo per gli altri 3 numeri nell'array `nums`, `1`, `2` e `3`. Poiché `count` viene incrementato di `1` 3 volte, il valore di `count` è `3`. + +

+
+ +--- + +###### 146. Qual è l'output? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Risposta +

+ +#### Risposta: D + +Il `?` ci consente di accedere opzionalmente a proprietà nidificate più profonde all'interno degli oggetti. Stiamo cercando di registrare l'elemento sull'indice `1` all'interno del sottoarray che si trova sull'indice `1` dell'array `fruits`. Se il sottoarray sull'indice `1` nell'array `fruits` non esiste, restituirà semplicemente `undefined`. Se il sottoarray sull'indice `1` nell'array `fruits` esiste, ma questo sottoarray non ha un elemento nel suo indice `1`, restituirà comunque `undefined`. + +Innanzitutto, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍍']` di `[['🍊', '🍌'], ['🍍']]`. Questo sottoarray contiene solo un elemento, il che significa che non c'è alcun elemento nell'indice `1`, e restituisce `undefined`. + +Quindi, stiamo invocando la funzione `getFruits` senza passare un valore come argomento, il che significa che `fruits` ha un valore di `undefined` per impostazione predefinita. Poiché stiamo concatenando condizionatamente l'elemento sull'indice `1` di `fruits`, restituisce `undefined` poiché questo elemento sull'indice `1` non esiste. + +Infine, stiamo cercando di registrare il secondo elemento nel sottoarray `['🍊', '🍌']` di `['🍍'], ['🍊', '🍌']`. L'elemento nell'indice `1` all'interno di questo sottoarray è `🍌`, che viene registrato. +

+
+ +--- + +###### 147. Qual è l'output? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +Impostiamo la variabile `calc` uguale a una nuova istanza della classe `Calc`. Quindi, istanziamo una nuova `Calc` e invochiamo il metodo `increase` su questa istanza. Poiché la proprietà count è all'interno del costruttore della classe `Calc`, la proprietà count non è condivisa sul prototipo di `Calc`. Ciò significa che il valore di count non è stato aggiornato per l'istanza a cui punta il calc, count è ancora `0`. +

+
+ +--- + +###### 148. Qual è l'output? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +La funzione `updateUser` aggiorna i valori delle proprietà `email` e `password` sull'utente se i loro valori vengono passati alla funzione, dopodiché la funzione restituisce l'oggetto `user`. Il valore restituito dalla funzione `updateUser` è l'oggetto `user`, il che significa che il valore di `updateUser` è un riferimento allo stesso oggetto `user` a cui punta `user`. `updatedUser === user` è uguale a `true`. + +

+
+ +--- + +###### 149. Qual è l'output? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Risposta +

+ +#### Risposta: C + +Per prima cosa, invochiamo il metodo `slice` sull'array fruit. Il metodo slice non modifica l'array originale, ma restituisce il valore che ha tagliato fuori dall'array: l'emoji banana. +Quindi, invochiamo il metodo `splice` sull'array fruit. Il metodo splice modifica l'array originale, il che significa che l'array fruit ora è composto da `['🍊', '🍎']`. +Infine, invochiamo il metodo `unshift` sull'array `fruit`, che modifica l'array originale aggiungendo il valore fornito, '🍇' in questo caso, come primo elemento nell'array. L'array fruit ora è composto da `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Qual è l'output? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: B + +Le chiavi degli oggetti vengono convertite in stringhe. + +Poiché il valore di `dog` è un oggetto, `animals[dog]` significa in realtà che stiamo creando una nuova proprietà chiamata `"object Object"` uguale al nuovo oggetto. +`animals["object Object"]` è ora uguale a `{ emoji: "🐶", name: "Mara"}`. + +Anche `cat` è un oggetto, il che significa che `animals[cat]` in realtà stiamo sovrascrivendo il valore di `animals["object Object"]` con le nuove proprietà cat. + +Loggando `animals[dog]`, o effettivamente `animals["object Object"]`, poiché la conversione dell'oggetto `dog` in una stringa risulta `"object Object"`, restituisce `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Qual è l'output? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Risposta +

+ +#### Risposta: A + +La funzione `updateEmail` è una arrow function e non è legata all'oggetto `user`. Ciò significa che la parola chiave `this` non si riferisce all'oggetto `user`, ma in questo caso si riferisce allo scope globale. Il valore di `email` all'interno dell'oggetto `user` non viene aggiornato. Quando si stampa il valore di `user.email`, viene restituito il valore originale ovvero `my@email.com`. + +

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

+ +#### Risposta: D + +Il metodo `Promise.all` esegue le promise passate in parallelo. Se una promise fallisce, il metodo `Promise.all` effettua un _rejects_ con il valore della promise rifiutata. In questo caso, `promise3` ha rifiutato con il valore `"Third"`. Stiamo rilevando il valore rifiutato nel metodo `catch` concatenato sulla chiamata `runPromises` per rilevare eventuali errori all'interno della funzione `runPromises`. Solo `"Third"` viene registrato, poiché `promise3` viene rifiutato con questo valore. + +

+
+ +--- + +###### 153. Quale dovrebbe essere il valore di `method` per loggare ` {nome: "Lydia", età: 22} `? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Risposta +

+ +#### Risposta: C + +Il metodo `fromEntries` trasforma un array 2d in un oggetto. Il primo elemento in ogni sottoarray sarà la chiave e il secondo elemento in ogni sottoarray sarà il valore. In questo caso, stiamo mappando sull'array `keys`, che restituisce un array il cui primo elemento è l'elemento nell'array di chiavi sull'indice corrente e il secondo elemento è l'elemento dell'array di valori sull'indice corrente. + +Questo crea una matrice di sottoarray contenenti le chiavi e i valori corretti, che risulta in `{ nome: "Lydia", età: 22 }` + +

+
+ +--- + +###### 154. Qual è l'output? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Risposta +

+ +#### Risposta: C + +Il valore predefinito di `address` è un oggetto vuoto `{}`. Quando abbiamo impostato la variabile `member` uguale all'oggetto restituito dalla funzione `createMember`, non abbiamo passato un valore per `address`, il che significa che il valore di `address` è l'oggetto vuoto predefinito `{}`. Un oggetto vuoto è un valore veritiero, il che significa che la condizione `address ? address : null` restituisce `true`. Il valore di `address` è l'oggetto vuoto `{}`. + +

+
+ +--- + +###### 155. Qual è l'output? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Risposta +

+ +#### Risposta: B + +La condizione all'interno dell'istruzione `if` controlla se il valore di `!typeof randomValue` è uguale a `"string"`. L'operatore `!` converte il valore in un valore booleano. Se il valore è vero, il valore restituito sarà `false`, se il valore è falso, il valore restituito sarà `true`. In questo caso, il valore restituito di `typeof randomValue` è il vero valore `"number"`, il che significa che il valore di `!typeof randomValue` è il valore booleano `false`. + +`!typeof randomValue === "string"` restituisce sempre false, poiché stiamo effettivamente controllando `false === "string"`. Poiché la condizione ha restituito `false`, il blocco di codice dell'istruzione `else` viene eseguito e `Yay it's a string!` viene registrato. + +

+
diff --git a/ja-JA/README-ja_JA.md b/ja-JA/README-ja_JA.md index 7d42eeeb..577982ce 100644 --- a/ja-JA/README-ja_JA.md +++ b/ja-JA/README-ja_JA.md @@ -8,23 +8,28 @@ 利用可能な言語リスト: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -854,7 +859,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1080,7 +1085,7 @@ typeof sayHi(); `sayHi`関数は、即時呼び出し関数式(IIFE)の戻り値を返します。この関数は`0`を返しました。それは`"number"`型です。 -参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, そして`symbol`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。 +参考:7つの組み込み型しかありません: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, そして `bigint`。関数はオブジェクトなので、`"function"`型ではなく`"object"`型です。

diff --git a/ko-KR/README-ko_KR.md b/ko-KR/README-ko_KR.md index 8ed66536..51411b6b 100644 --- a/ko-KR/README-ko_KR.md +++ b/ko-KR/README-ko_KR.md @@ -1,33 +1,51 @@ -# (고급) JavaScript 질문 목록 +
+ +

JavaScript 질문

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

-사용 가능한 언어 목록: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

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

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

정답 +

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

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

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

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

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

정답 +

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

@@ -828,12 +846,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -841,12 +859,12 @@ name.giveLydiaPizza(); - C: `SyntaxError` - D: `undefined` -
정답 +

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

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

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

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

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

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

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

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

- Click here! -

+

Click here!

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

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

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

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

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

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

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

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

정답 +

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

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

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

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

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

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

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

정답 +

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

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

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

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

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

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

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

--- -###### 86. `true`를 인수로 전달 할 수 없도록 주어졌을 때, `hasName`을 `true`로 설정할 수 있는 방법은 어느 것 일까요? +###### 86. `true`를 인수로 전달 할 수 없도록 주어졌을 때, `hasName`을 `true`로 설정할 수 있는 방법은 어느 것일까요? ```javascript function getName(name) { @@ -2716,18 +2734,18 @@ function getName(name) { - C: `new Boolean(name)` - D: `name.length` -
정답 +

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@@ -3313,22 +3329,22 @@ for (let item of set) { ###### 104. 값은 무엇일까요? ```javascript -Promise.resolve(5) +Promise.resolve(5); ``` - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error` -
정답 +

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

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

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

정답 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+
+ +--- + +###### 127. 무엇이 출력 될까요? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); -`changeAge`와 `changeAgeAndName`함수 둘다 기본 파라미터를 가지고 있는데 즉, _새롭게_ 만들어진 객체 `{ ...person }`를 가지고 있어요. 이 객체는 `person` 객체의 모든 키/값의 복사본을 가지고 있어요. +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
+

-첫번째로, `changeAge`함수를 호출 했고, 그것의 인수로 `person` 객체를 전달 했어요. 이 함수는 `age`속성의 값을 1 증가 시켜요. `person`은 이제 `{ name: "Lydia", age: 22 }`이에요. +#### 답: B -그리고나서, `changeAgeAndName` 함수를 호출 했지만, 파라미터를 전달하지 않았어요. 대신에, `x`의 값은 _새로운_ 객체와 같아요: `{ ...person }`. 새로운 객체이기 때문에, `person`객체의 속성들의 값에 영향을 주지 않아요. `person`은 여전히 `{ name: "Lydia", age: 22 }`와 같아요. +객체를 분해함으로써, 오른쪽 객체의 값을 꺼내고, 꺼낸 값은 왼쪽 객체에 같은 속성 이름의 값으로 할당 할 수 있어요. 이 경우, 값 "💀"을 `spookyItems[3]`에 할당했어요. 이건 `spookyItems`을 수정, 즉 배열에 "💀"을 추가한다는 의미예요. `spookyItems`을 출력하면, `["👻", "🎃", "🕸", "💀"]`이 출력ㅗ대요.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+
+ +--- + +###### 137. 다음 중 어느 것이 `person` 객체를 수정 할 수 있을까요? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
+

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

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

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

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

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

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

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

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

+ +#### 답: C + +`addHobby` 함수는 인수 두 개 `hobby` 와 `person` 객체의 배열 `hobbies`의 값을 기본값으로 가진 `hobbies`를 받아요. + +우선, `addHobby` 함수를 호출하고, `hobby`의 값으로 `"running"`을 그리고 `hobbies`의 값으로 빈 배열을 전달해요. `hobbies`의 값으로 빈 배열을 전달했기 때문에, `"running"`은 빈 배열에 추가돼요. + +그리고서, `addHobby` 함수를 호출하고, `hobby`의 값으로 `"dancing"`를 전달해요. `hobbies`에 값을 전달하지 않았고, `person` 객체의 속성 `hobbies`을 기본값으로 가져요. 배열 `person.hobbies`에 `dancing`를 추가해요. + +마지막으로, `addHobby` 함수를 호출해, `hobby`의 값으로 `"baking"`를 전달하고, `hobbies`의 값으로 배열 `person.hobbies`을 전달해요. 배열 `person.hobbies`에 `baking`을 추가해요. + +`dancing` 과 `baking`을 추가한 후, `person.hobbies`의 값은 `["coding", "dancing", "baking"]`예요. + +

+
+ +--- + +###### 142. 무엇이 출력 될까요? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
+

+ +#### 답: B + +`Flamingo` 클래스의 인스턴스인 변수 `pet` 생성했어요. 인스턴스를 인스턴스화 할 때, `Flamingo`의 `constructor`를 불러요. 우선, `"I'm pink. 🌸"`가 출력되고, 그 후에 `super()`를 불러요. `super()`는 부모 클래스 `Bird`의 constructor를 불러요. `Bird`의 constructor 를 불러, `"I'm a bird. 🦢"`가 출력돼요. + +

+
+ +--- + +###### 143. 다음 중 어느 것의 결과가 오류일까요? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
+

+ +#### 답: D + +`const` 키워드는 단순히 변수의 값을 _재선언_ 할 수 없고, _읽기만_ 가능하다는 의미예요. 하지만, 값 자체가 불변하는 건 아니에요. 배열 `emojis`의 속성을 수정할 수 있는데, 예를 들자면 새로운 값을 추가하거나, 원본 배열 자체를 수정(splice)하거나, 배열의 길이를 0으로 설정 할 수 있어요. + +

+
+ +--- + +###### 144. `person`에 무엇을 추가해야 `[...person]`의 결과로 `["Lydia Hallie", 21]`를 얻을 수 있을까요? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: 객체는 기본적으로 반복 가능 하므로, 아무것도 하지 않아요. +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
+

+ +#### 답: C + +객체는 기본적으로 반복 불가능해요. 반복 가능한 객체는 iterator protocol이 제공되면 반복 가능해요. 제너레이터 함수 `*[Symbol.iterator]() {}`을 만드는 제너레이터 객체를 반환하는 iterator symbol `[Symbol.iterator]`을 수동으로 추가 할 수 있어요. 배열 `["Lydia Hallie", 21]`을 반환 하려면 제너레이터 함수는 `person` 객체의 `Object.values`를 yield 해야해요: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. 무엇이 출력 될까요? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach((num) => { + if (num) count += 1; +}); + +console.log(count); +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
+

+ +#### 답: C + +`forEach` 순환에 포함 된 `if` 조건문은 `num`의 값이 진짜 같은 값인지 또는 가짜 같은 값인지 확인해요. `nums`배열의 첫 번째 값은 거짓 같은 값 `0`이고, `if` 조건문의 코드 블럭은 실행되지 않아요. `count` 는 오직 `nums` 배열의 다른 숫자 3개에 대해서만 증가해요. `1`, `2` 그리고 `3`. `count`는 3번 동안 `1` 씩 증가하고, `count`의 값은 `3`이에요. + +

+
+ +--- + +###### 146. 무엇이 출력 될까요? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]); +} + +getFruit([['🍊', '🍌'], ['🍍']]); +getFruit(); +getFruit([['🍍'], ['🍊', '🍌']]); +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
+

+ +#### 답: D + +`?`는 객체 내에서 더 깊이 중첩된 속성에 접근하는 것을 선택적으로 허용해요. `fruits`배열의 인덱스 `1`에 있는 하위 배열의 인덱스 `1`의 아이템을 출력하려해요. `fruits`배열의 인덱스 `1`에 하위 배열이 존재하지 않는다면, 간단히 `undefined`를 반환할 거예요. `fruits` 배열의 인덱스 `1`에 하위배열이 있지만, 하위 배열에 인덱스 `1` 의 아이템이 없다면, 그것 역시 `undefined`를 반환해요. + +우선, `[['🍊', '🍌'], ['🍍']]`의 하위 배열의 두 번째 아이템 `['🍍']`을 출력해요 . 하위 배열은 아이템 하나만 가지고 있고, 이건 인덱스 `1`에 대한 아이템을 갖고 있지 않다는 의미로 `undefined`를 반환해요. + +그리고서, 인수에 어떤 값도 전달하지 않은 `getFruits` 함수를 호출 하고, `fruits`은 기본값으로 값 `undefined`을 가져요. `fruits`의 인덱스 `1`의 아이템을 선택적으로 연결(conditionally chaining)하기 때문에, 인덱스 `1`에 아이템이 존재하지 않아 `undefined`를 반환해요. + +마지막으로, `['🍍'], ['🍊', '🍌']`의 하위 배열 `['🍊', '🍌']`의 두번째 아이템을 출력하려고 해요. 하위 배열의 인덱스 `1`의 아이템인 `🍌`이 출력돼요. + +

+
+ +--- + +###### 147. 무엇이 출력 될까요? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: A + +변수 `calc`를 `Calc` 클래스의 새로운 인스턴스로 설정 했어요. 그리고서, 새로운 인스턴스 `Calc`를 인스턴스화 하고, 이 인스턴스의 `increase` 메소드를 호출 했어요. 속성 count은 `Calc` 클래스의 생성자 안에 있기 때문에 , 속성 count은 `Calc`의 프로토타입에 공유될 수 없어요. 인스턴스 calc이 가리키는 count의 값은 업데이트 되지 않고, count는 여전히 `0`예요. + +

+
+ +--- + +###### 148. 무엇이 출력 될까요? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
+

+ +#### 답: B + +`updateUser` 함수는 값이 전달 되면 user의 속성 `email` 과 `password`의 값을 업데이트 하고, `user`객체를 반환해요. `updateUser` 함수의 반환된 값은 객체 `user` 이고, updateUser의 값은 `user`가 가리키는 `user` 객체의 참조와 같다는 의미예요. `updatedUser === user`는 `true`예요. + +

+
+ +--- + +###### 149. 무엇이 출력 될까요? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
+

+ +#### 답: C + +우선, fruit 배열에 `slice` 메소드를 호출해요. slice 메소드는 원본 배열을 수정하지 않지만, 배열에서 잘라낸(slice) 값을 반환해요: 바나나 이모지. +그리고서, fruit 배열에 `splice` 메소드를 호출해요. splice 메소드는 원본 배열을 수정하고, 이제 fruit 배열은 `['🍊', '🍎']`로 구성돼요. +마지막엔, `fruit` 배열에 `unshift` 메소드를 호출하고, 이 경우엔 제공된 값 ‘🍇’을 배열의 첫 번째 요소로 추가해 원본 배열을 수정해요. 이제 fruit 배열은 `['🍇', '🍊', '🍎']`로 구성돼요. + +

+
+ +--- + +###### 150. 무엇이 출력 될까요? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: B + +객체의 키는 문자열로 변환돼요. + +`dog`의 값은 객체 이므로, 사실 `animals[dog]`는 새로운 객체에 `"object Object"`라고 불리는 새로운 속성을 만든 걸 의미해요. 이제 `animals["object Object"]`는 `{ emoji: "🐶", name: "Mara"}`예요. + +`cat`도 물론 객체고, 사실 `animals[cat]`은 `animals[``"``object Object``"``]`을 새로운 속성 cat으로 덮어쓰고 있다는 것을 의미해요. + +`animals[dog]` 또는 `animals["object Object"]`(`dog` 객체를 문자열로 변환한 결과는 `"object Object"`)를 출력하면, `{ emoji: "🐈", name: "Sara" }`를 반환해요. + +

+
+ +--- + +###### 151. 무엇이 출력 될까요? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
+

+ +#### 답: A + +`updateEmail`함수는 화살표 함수로, `user`객체에 바인딩 되지 않았어요. `this`키워드는 `user`객체를 참조하지 않지만, 이 경우엔 전역 범위를 참조하고 있다는 의미예요. `user` 객체의 `email` 는 업데이트 되지 않아요. `user.email`을 출력할 때, `my@email.com`의 원래의 값이 반환되어요. + +

+
+ +--- + +###### 152. 무엇이 출력 될까요? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
+

+ +#### 답: D + +`Promise.all` 메소드는 프로미스를 병렬로 실행해요. 만약 하나의 프로미스가 실패하면, `Promise.all` 메소드는 rejected 프로미스의 값을 가지고 _rejects_ 되어요. 이 경우, `promise3`는 값 `"Third"`과 함께 rejected 되었어요. `runPromises` 호출에 연결되어 있고 `runPromises` 함수 안에서 모든 에러를 잡은 `catch` 메소드에서 rejected 값을 잡아요. `promise3`가 이 값과 함께 rejected 되어 `"Third"`만 출력돼요. + +

+
+ +--- + +###### 153. 무엇이 `method`의 값이어야 `{ name: "Lydia", age: 22 }`를 출력할까요? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
+

+ +#### 답: C + +`fromEntries` 메소드는 2차원 배열을 객체로 변환해요. 각 하위 배열의 첫번 째 요소는 키가 될거고, 각 하위 배열의 요소의 두번째 요소는 값이 될거에요. 이 경우엔, keys배열에서 현재 인덱스의 아이템을 첫 번재 요소로, values의 배열에서 현재 인덱스의 아이템을 두번째 요소로 반환하는 `keys` 배열을 매핑해요. + +키와 값의 집합을 포함하고 있는 하위 배열을 만들었고, `{ name: "Lydia", age: 22 }`가 되어. + +

+
+ +--- + +###### 154. 무엇이 출력 될까요? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
+

+ +#### 답: C + +`address`의 기본 값은 빈 객체 `{}`예요. 변수 `member`의 값을 `createMember` 함수에서 반환한 값으로 설정하고, address의 값을 전달하지 않았어요, address의 값은 빈 객체 `{}`가 기본 값이예요. 빈객체는 진짜 같은 값으로, 조건 `address ? address : null`에서 `true`를 반환한다는 의미예요. address의 값은 빈 객체 `{}`예요. + +

+
+ +--- + +###### 155. 무엇이 출력 될까요? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
+

+ +#### 답: B + +`if`문 안에 조건은 `!typeof randomValue`값이 `"string"`와 같은지 여부를 확인해요. `!` 연산자는 값을 불리언 값으로 변환해요. 값이 진짜 같은 값이라면 반환될 값은 `false`가 될 거고, 만약 값이 가짜 같은 값이라면 반환될 값은 `true`가 될 거예요. 이 경우에서, `typeof randomValue`의 반환된 값은 진짜 같은 값인 `"number"`이고, `!typeof randomValue`의 값은 불리언 값 `false`라는 의미예요. + +`!typeof randomValue === "string"`은 실제로 `false === "string"`을 확인하기 때문에 항상 false를 반환해요. 조건은 `false`을 반환 하므로, `else`문의 코드 블록이 실행되어 `Yay it's a string!`가 출력돼요. + +

+
diff --git a/nl-NL/README.md b/nl-NL/README.md index 635dcd30..ffc14a97 100644 --- a/nl-NL/README.md +++ b/nl-NL/README.md @@ -17,23 +17,28 @@
Zie alle 17 beschikbare vertalingen

-* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md)

@@ -843,7 +848,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1060,7 +1065,7 @@ console.log(typeof sayHi()); De `sayHi` functie geeft de waarde terug van de direct aangeroepen functie (IIFE). Deze functie geeft `0` terug, die het type `number` heeft. -FYI: er zijn slechts 7 ingebouwde types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, en `symbol`. `"function"` is geen type omdat functies objecten zijn, en dus van het type `"object"`. +FYI: er zijn slechts 7 ingebouwde types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` en `bigint`. `"function"` is geen type omdat functies objecten zijn, en dus van het type `"object"`.

@@ -3325,7 +3330,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Antwoord @@ -3333,7 +3338,7 @@ Promise.resolve(5) #### Antwoord: C -We kunnen elk type of waarde meegeven aan `Promise.resolve`, zowel een promise als een niet-promise. De methode zelf retourneert een promise met een opgeloste waarde. Als je een reguliere functie meegeeft zal het een opgeloste promise zijn met een reguliere waarde. Als je een promise meegeeft zal het een opgeloste promise zijn met een opgeloste waarde, of de doorgegeven promise. +We kunnen elk type of waarde meegeven aan `Promise.resolve`, zowel een promise als een niet-promise. De methode zelf retourneert een promise met een opgeloste waarde (``). Als je een reguliere functie meegeeft zal het een opgeloste promise zijn met een reguliere waarde. Als je een promise meegeeft zal het een opgeloste promise zijn met een opgeloste waarde, of de doorgegeven promise. In dit geval geven we alleen de numerieke waarde `5` mee. Het geeft de opgeloste promise terug met de waarde `5`. @@ -4612,7 +4617,7 @@ console.log(person.hobbies); De functie `addHobby` ontvangt twee arguemnten, `hobby` en `hobbies` met als standaard waarde de waarde van de array `hobbies` op het object `person`. -Eerst roepen we de functie `addHobby` aan en geven `"running"` mee als de waarde voor `hobby`, en een lege array als de waarde voor `hobbies`. Omdat we een lege array meegeven als de waarde voor `y` wordt `"running"` toegevoegd aan deze lege array. +Eerst roepen we de functie `addHobby` aan en geven `"running"` mee als de waarde voor `hobby`, en een lege array als de waarde voor `hobbies`. Omdat we een lege array meegeven als de waarde voor `hobbies` wordt `"running"` toegevoegd aan deze lege array. Daarna roepen we de functie `addHobby` aan en geven `"dancing"` mee als de waarde voor `hobby`. We gaven geen waarde mee voor `hobbies` dus krijgt het de standaard waarde, de propertie `hobbies` op het object `person`. We pushen daar de hobby `dancing` naar de array `person.hobbies`. @@ -4713,4 +4718,4 @@ const person = { Objecten zijn standaard niet itereerbaar. Een _iterable_ is een _iterable_ als het _iterator protocol_ aanwezig is. We kunnen dit met de iterator symbol `[Symbol.iterator]` handmatig toevoegen, wat een generator object zal moeten teruggeven. Bijvoorbeeld door het een generator functie te maken: `*[Symbol.iterator]() {}`. Deze generator functie moet de `Object.values` afgeven van het object `person` als we de array `["Lydia Hallie", 21]`: `yield* Object.values(this)` terug willen geven.

-
\ No newline at end of file +
diff --git a/pl-PL/README.md b/pl-PL/README.md new file mode 100644 index 00000000..ef1c71d6 --- /dev/null +++ b/pl-PL/README.md @@ -0,0 +1,2391 @@ +
+ +

Pytania dotyczące JavaScript

+
+ +> [!NOTE] +> To repozytorium zostało utworzone w 2019 roku, a zatem pytania tutaj zawarte są oparte na składni i zachowaniu JavaScript w tym czasie. Ponieważ JavaScript jest stale rozwijającym się językiem, istnieją nowsze funkcje językowe, które nie są objęte pytaniami tutaj. + +--- + +

+Od podstawowych do zaawansowanych: sprawdź, jak dobrze znasz JavaScript, odśwież swoją wiedzę lub przygotuj się do rozmowy kwalifikacyjnej! :muscle: :rocket: Regularnie aktualizuję to repozytorium nowymi pytaniami. Odpowiedzi znajdują się w ukrytych zakładkach poniżej pytań - po prostu kliknij, aby je rozwinięć. To dla zabawy, powodzenia! :heart:

+ +

Nie krępuj się ze mną kontaktować! 😊

+ +

+Instagram || Twitter || LinkedIn || Blog +

+ +| Śmiało używaj ich w projekcie! 😃 Byłabym _bardzo_ wdzięczna za referencje do tego repozytorium, tworzę pytania i wyjaśnienia (tak, jestem smutna lol) i społeczność bardzo mi pomaga w utrzymaniu i ulepszaniu go! 💪🏼 Dziękuję i baw się dobrze! | +|---| + +--- + +
Zobacz 20 dostępnych tłumaczeń 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Jaki jest wynik? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` and `undefined` +- B: `Lydia` and `ReferenceError` +- C: `ReferenceError` and `21` +- D: `undefined` and `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Wewnątrz funkcji najpierw deklarujemy zmienną `name` za pomocą słowa kluczowego `var`. Oznacza to, że zmienna jest "wyciągana" (przestrzeń pamięci jest tworzona) z domyślną wartością `undefined` podczas fazy tworzenia, aż do momentu, gdy naprawdę definiujemy zmienną. W linii, w której próbujemy wyświetlić w konsoli zmienną `name`, jeszcze jej nie zdefiniowaliśmy, więc nadal przechowuje wartość `undefined`. + +Zmienne zadeklarowane za pomocą słowa kluczowego `let` (i `const`) są wyciągane, ale w przeciwieństwie do `var`, nie są inicjalizowane. Nie są dostępne przed linią, na której je deklarujemy (inicjalizujemy). Nazywa się to "czasową strefą martwą" (temporal dead zone). Gdy próbujemy uzyskać dostęp do zmiennych przed ich zadeklarowaniem, JavaScript generuje błąd `ReferenceError`. + +

+
+ +--- + +###### 2. Jaki jest wynik? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` and `0 1 2` +- B: `0 1 2` and `3 3 3` +- C: `3 3 3` and `0 1 2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Ze względu na kolejkę zdarzeń w JavaScript, funkcja zwrotna `setTimeout` jest wywoływana _po_ wykonaniu pętli. Ponieważ zmienna `i` w pierwszej pętli została zadeklarowana za pomocą słowa kluczowego `var`, jej wartość była globalna. Podczas pętli inkrementowaliśmy wartość `i` o `1` za każdym razem, używając operatora jednoargumentowego `++`. W momencie wywołania funkcji zwrotnej `setTimeout`, `i` miało wartość `3` w pierwszym przykładzie. + +W drugiej pętli zmienna `i` została zadeklarowana za pomocą słowa kluczowego `let`: zmienne zadeklarowane za pomocą słowa kluczowego `let` (i `const`) mają zakres blokowy (blokiem jest cokolwiek między `{ }`). Podczas każdej iteracji `i` będzie miało nową wartość, a każda wartość będzie miała zakres wewnątrz pętli. + +

+
+ +--- + +###### 3. Jaki jest wynik? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Zwróć uwagę, że wartość `diameter` jest zwykłą funkcją, podczas gdy wartość `perimeter` jest funkcją strzałkową. + +W przypadku funkcji strzałkowych, słowo kluczowe `this` odnosi się do bieżącego otaczającego zakresu, w przeciwieństwie do zwykłych funkcji! Oznacza to, że gdy wywołujemy `perimeter`, nie odnosi się ono do obiektu shape, ale do swojego otaczającego zakresu (np. okna). + +Na tym obiekcie nie ma wartości `radius`, co powoduje zwrócenie `NaN` (Not a Number). + +

+
+ +--- + +###### 4. Jaki jest wynik? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator jednoargumentowy plus próbuje przekonwertować operand na liczbę. `true` jest równoważne `1`, a `false` jest równoważne `0`. + +Łańcuch znaków `'Lydia'` jest wartością prawdziwą. Tak naprawdę pytamy, "czy ta wartość prawdziwa jest fałszywa?". To zwraca `false`. + +

+
+ +--- + +###### 5. Które jest prawdziwe? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` is not valid +- B: `mouse[bird.size]` is not valid +- C: `mouse[bird["size"]]` is not valid +- D: All of them are valid + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript wszystkie klucze obiektów są stringami (chyba że są to symbole). Nawet jeśli nie wpisujemy ich jako stringi, zawsze są one konwertowane na stringi wewnątrz. + +JavaScript interpretuje (lub "odpakuowuje") instrukcje. Gdy używamy notacji nawiasów kwadratowych, interpreter widzi pierwszy otwierający nawias `[` i kontynuuje do momentu znalezienia zamykającego nawiasu `]`. Dopiero wtedy ocenia tę instrukcję. + +`mouse[bird.size]`: Najpierw ocenia `bird.size`, które wynosi `"small"`. `mouse["small"]` zwraca `true`. + +Jednakże, w przypadku notacji kropkowej, to się nie dzieje. `mouse` nie ma klucza o nazwie `bird`, co oznacza, że `mouse.bird` jest `undefined`. Następnie pytamy o `size` używając notacji kropkowej: `mouse.bird.size`. Ponieważ `mouse.bird` jest `undefined`, tak naprawdę pytamy o `undefined.size`. To nie jest poprawne i spowoduje błąd podobny do `Cannot read property "size" of undefined` (Nie można odczytać właściwości "size" z undefined). + +

+
+ +--- + +###### 6. Jaki jest wynik? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript wszystkie obiekty komunikują się ze sobą przez _referencje_, gdy są sobie przypisywane. + +Na początku zmienna `c` przechowuje referencję do obiektu. Później przypisujemy zmiennej `d` tę samą referencję, którą ma `c`, do tego obiektu. + + + +Kiedy zmieniasz jeden obiekt, zmieniasz je wszystkie. + +

+
+ +--- + +###### 7. Jaki jest wynik? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`new Number()` jest wbudowanym konstruktorem funkcji. Chociaż wygląda jak liczba, nie jest faktycznie liczbą: ma wiele dodatkowych funkcji i jest obiektem. + +Gdy używamy operatora `==` (operator równości), sprawdza on jedynie, czy mają tą samą _wartość_. Oba mają wartość `3`, więc zwraca `true`. + +Jednak gdy używamy operatora `===` (operator ścisłej równości), zarówno wartość, jak i typ powinny być takie same. Tutaj nie są: `new Number()` nie jest liczbą, lecz **obiektem**. Oba zwracają `false`. + +

+
+ +--- + +###### 8. Jaki jest wynik? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Funkcja `colorChange` jest statyczna. Metody statyczne są zaprojektowane tak, aby istniały tylko w konstruktorze, w którym zostały utworzone, i nie mogą być przekazywane do żadnych potomków (children) ani wywoływane na instancjach klasy. Ponieważ `freddie` jest instancją klasy Chameleon, funkcja nie może być na niej wywołana. Otrzymujemy błąd `TypeError`. + +

+
+ +--- + +###### 9. Jaki jest wynik? + +```javascript +let greeting; +greetign = {}; // Celowa Literówka! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Kod wypisuje w konsoli obiekt, ponieważ właśnie utworzyliśmy pusty obiekt w obiekcie globalnym! Gdy pomyłkowo wpisaliśmy `greeting` jako `greetign`, interpreter JavaScript faktycznie zobaczył to jako: + +1. `global.greetign = {}` w Node.js. +2. `window.greetign = {}`, `frames.greetign = {}` i `self.greetign` w przeglądarkach. +3. `self.greetign` w web workerach. +4. `globalThis.greetign` we wszystkich środowiskach. + +Aby temu zapobiec, możemy użyć `"use strict"`. Powoduje to, że musisz zadeklarować zmienną przed jej przypisaniem. + +

+
+ +--- + +###### 10. Co się dzieje, gdy to zrobimy? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Nothing, this is totally fine! +- B: `SyntaxError`. You cannot add properties to a function this way. +- C: `"Woof"` gets logged. +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Jest to możliwe w JavaScript, ponieważ funkcje są obiektami! (Wszystko oprócz typów prymitywnych jest obiektem) + +Funkcja jest specjalnym rodzajem obiektu. Kod, który sam piszesz, nie jest właściwą funkcją. Funkcja jest obiektem posiadającym właściwość, która jest wywoływalna. + +

+
+ +--- + +###### 11. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +W JavaScript funkcje są obiektami, więc metoda `getFullName` jest dodawana do samego obiektu funkcji konstruktora. Dlatego możemy wywołać `Person.getFullName()`, ale `member.getFullName` zwraca błąd `TypeError`. + +Jeśli chcesz, aby metoda była dostępna dla wszystkich instancji obiektów, musisz dodać ją do właściwości prototype: + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Jaki jest wynik? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Dla `sarah`, nie użyliśmy słowa kluczowego `new`. Kiedy używamy `new`, `this` odwołuje się do nowego pustego obiektu, który tworzymy. Jednak jeśli nie dodajemy `new`, `this` odwołuje się do **globalnego obiektu**! + +Mówiliśmy, że `this.firstName` równa się `"Sarah"`, a `this.lastName` równa się `"Smith"`. Czyli faktycznie zdefiniowaliśmy `global.firstName = 'Sarah'` i `global.lastName = 'Smith'`. `sarah` pozostaje `undefined`, ponieważ nie zwracaliśmy żadnej wartości z funkcji `Person`. + +

+
+ +--- + +###### 13. Jakie są trzy fazy propagacji zdarzeń? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Odpowiedź +

+ +#### Odpowiedź: D + +W fazie **capturing (przechwytywanie)**, zdarzenie przechodzi przez elementy nadrzędne w doł do elementu docelowego. Następnie dociera do elementu **target (cel)** i rozpoczyna się **bubbling (bąbelkowanie)**. + + + +

+
+ +--- + +###### 14. Wszystkie obiekty mają prototypy. + +- A: true +- B: false + +
Odpowiedź +

+ +#### Odpowiedź: B + +Wszystkie obiekty mają prototypy, z wyjątkiem **obiektu bazowego**. Obiekt bazowy jest obiektem utworzonym przez użytkownika lub obiektem utworzonym przy użyciu słowa kluczowego `new`. Obiekt bazowy ma dostęp do niektórych metod i właściwości, takich jak `.toString`. Jest to powód, dla którego można używać wbudowanych metod JavaScript! Wszystkie takie metody są dostępne w prototypie. Chociaż JavaScript nie może znaleźć ich bezpośrednio w twoim obiekcie, przechodzi w dół łańcucha prototypów i je tam znajduje, co czyni je dostępnymi dla ciebie. + +

+
+ +--- + +###### 15. Jaki jest wynik? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Odpowiedź +

+ +#### Odpowiedź: C + +JavaScript jest językiem **dynamicznie typowanym**: nie określamy typów niektórych zmiennych. Wartości mogą być automatycznie konwertowane na inny typ bez wiedzy użytkownika, co nazywa się _implicit type coercion_. **Koercja (Wymuszenie)** to konwersja z jednego typu na inny. + +W tym przykładzie JavaScript konwertuje liczbę `1` na string, aby funkcja miała sens i zwróciła wartość. Podczas dodawania typu liczbowego (`1`) i typu łańcuchowego (`'2'`), liczba traktowana jest jako string. Możemy łączyć stringi takie jak `"Hello" + "World"`, więc to co się tutaj dzieje to `"1" + "2"`, które zwraca `"12"`. + +

+
+ +--- + +###### 16. Jaki jest wynik? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Operator jednoargumentowy **Postfix** `++`: + +1. Zwraca wartość (ten zwraca `0`) +2. Zwiększa wartość (liczba wynosi teraz `1`) + +Operator jednoargumentowy **Prefix** `++`: + +1. Zwiększa wartość (liczba wynosi teraz `2`) +2. Zwraca wartość (to zwraca `2`) + +number zwraca `0 2 2`. + +

+
+ +--- + +###### 17. Jaki jest wynik? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Odpowiedź +

+ +#### Odpowiedź: B + +W przypadku użycia `template strings`, wartością pierwszego argumentu jest zawsze tablica wartości łańcuchowych (string). Pozostałe argumenty otrzymują wartości przekazanych wyrażeń! + +

+
+ +--- + +###### 18. Jaki jest wynik? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Podczas testowania równości, liczby i ciągi znaków są porównywane przez ich _wartości_, a obiekty są porównywane przez ich _referencję_. JavaScript sprawdza, czy obiekty mają odwołanie do tej samej lokalizacji w pamięci. + +Dwa obiekty, które porównujemy, nie mają tej samej lokalizacji w pamięci: obiekt, który przekazujemy jako parametr, odwołuje się do innej lokalizacji w pamięci niż obiekt, którego użyliśmy do sprawdzenia równości. + +Dlatego też zarówno `{ age: 18 } == { age: 18 }` i `{ age: 18 } == { age: 18 }` zwracają `false`. + +

+
+ +--- + +###### 19. Jaki jest wynik? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Parametr reszty (`...args`) pozwala nam "zbierać" wszystkie pozostałe argumenty do tablicy. Tablica to obiekt, więc `typeof args` zwraca `"object"`. + +

+
+ +--- + +###### 20. Jaki jest wynik? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Dzięki `"use strict"` możesz upewnić się, że przypadkowo nie zadeklarujesz zmiennych globalnych. Nigdy nie zadeklarowaliśmy zmiennej `age`, a ponieważ używamy `"use strict"`, zostanie zgłoszony błąd referencji. Gdybyśmy nie użyli `"use strict"`, to by zadziałało, ponieważ właściwość `age` zostałaby dodana do obiektu globalnego. + +

+
+ +--- + +###### 21. Jaka jest wartość `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`eval` oblicza kod, który przekazywany jest jako ciąg znaków. Jeśli jest to wyrażenie, tak jak w tym przypadku, oblicza ono wyrażenie. Wyrażenie to `10 * 10 + 5`. Zwraca liczbę `105`. + +

+
+ +--- + +###### 22. Jak długo cool_secret jest dostępny? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Dane nigdy nie zostaną utracone. +- B: Gdy użytkownik zamyka kartę. +- C: Gdy użytkownik zamyka cały przeglądarkę, a nie tylko kartę. +- D: Gdy użytkownik wyłącza swój komputer. + +
Odpowiedź +

+ +#### Odpowiedź: B + +Dane przechowywane w `sessionStorage` są usuwane po zamknięciu _zakładki_. + +Gdybyś użył `localStorage`, dane pozostałyby tam na zawsze, chyba że na przykład wywołano by `localStorage.clear()`. + +

+
+ +--- + +###### 23. Jaki jest wynik? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą słowa kluczowego `var` można zadeklarować wiele zmiennych o tej samej nazwie. Zmienna będzie wtedy przechowywać najnowszą wartość. + +Nie można tego zrobić za pomocą `let` lub `const`, ponieważ są one blokowe. + +

+
+ +--- + +###### 24. Jaki jest wynik? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Wszystkie klucze obiektów (z wyjątkiem symboli) są łańcuchami znaków pod względem samego obiektu, nawet jeśli nie napiszesz ich samodzielnie jako łańcucha znaków. Dlatego `obj.hasOwnProperty('1')` również zwraca true. + +Nie działa to w ten sam sposób dla zbioru. W zbiorze nie ma klucza `'1'`:`set.has('1')`, dlatego zwraca wartość false. Zawiera on liczbę całkowitą `1`, `set.has(1)` zwraca wartość true. + +

+
+ +--- + +###### 25. Jaki jest wynik? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Jeśli masz dwa klucze o takiej samej nazwie, zostanie on zastąpiony. Nadal będzie umieszczony na pierwszej pozycji, ale z ostatnią zdefiniowaną wartością. + +

+
+ +--- + +###### 26. Globalny kontekst wykonania JavaScript tworzy dwie rzeczy: obiekt globalny i słowo kluczowe "this". + +- A: true +- B: false +- C: it depends + +
Odpowiedź +

+ +#### Odpowiedź: A + +Globalny kontekst wykonania jest dostępny wszędzie w kodzie. + +

+
+ +--- + +###### 27. Jaki jest wynik? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Instrukcja `continue` pomija iterację, jeśli określony warunek zwróci `true`. + +

+
+ +--- + +###### 28. Jaki jest wynik? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`String` jest wbudowanym konstruktorem, do którego możemy dodawać właściwości. Dodana została metoda do jego prototypu. Prymitywne ciągi znaków są automatycznie konwertowane na obiekt typu string, generowany przez funkcję prototypu ciągu znaków. Tak więc wszystkie ciągi (obiekty typu string) mają dostęp do tej metody! + +

+
+ +--- + +###### 29. Jaki jest wynik? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Klucze obiektów są automatycznie konwertowane na ciągi znaków. Próbujemy ustawić obiekt jako klucz do obiektu `a`, z wartością `123`. + +Jednakże, kiedy stringujemy obiekt, staje się on `"[obiekt Object]"`. Mówimy więc, że `a["[obiekt Object]"] = 123`. Następnie próbujemy zrobić to samo. `c` jest kolejnym obiektem, który niejawnie stringujemy. Zatem `a["[obiekt Object]"] = 456`. + +Następnie wyświetlamy w konsoli `a[b]`, co w rzeczywistości jest `a["[obiekt Object]"]`, ustawiony wcześniej na `456`, więc zwraca `456`. + +

+
+ +--- + +###### 30. Jaki jest wynik? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Mamy funkcję `setTimeout` i wywołaliśmy ją jako pierwszą. Została jednak wyświetlona jako ostatnia. + +Dzieje się tak, ponieważ w przeglądarkach mamy nie tylko silnik wykonawczy, ale także coś, co nazywa się `WebAPI`. Interfejs `WebAPI` daje nam na początek funkcję `setTimeout`. + +Po przesłaniu _callback_ do WebAPI, sama funkcja `setTimeout` (ale nie callback!) jest usuwana ze stosu. + + + +Teraz, `foo` jest wywoływane, a `"First"` jest wyświetlane. + + + +`foo` jest zdejmowane ze stosu, a `baz` jest wywoływane. "Third" zostaje wyświetlony. + + + +WebAPI nie może dodawać rzeczy do stosu, gdy jest gotowy. Zamiast tego przesuwa funkcję zwrotną do czegoś zwanego _kolejką_. + + + +W tym miejscu zaczyna działać pętla zdarzeń. **Pętla zdarzeń** patrzy na stos i kolejkę zadań. Jeśli stos jest pusty, pobiera pierwszą rzecz z kolejki i przesuwa ją na stos. + + + +`bar` zostaje wywołany, `"Second"` zostaje wyświetlony i zdjęty ze stosu. + +

+
+ +--- + +###### 31. Co zostanie wyświetlone w konsoli po kliknięciu przycisku? + +```html +
+
+ +
+
+``` + +- A: Zewnętrzny `div` +- B: Wewnętrzny `div` +- C: `button` +- D: Tablica wszystkich zagnieżdżonych elementów. + +
Odpowiedź +

+ +#### Odpowiedź: C + +Najgłębiej zagnieżdżony element, który spowodował zdarzenie jest celem zdarzenia. Możesz zatrzymać bąbelkowanie poprzez `event.stopPropagation` + +

+
+ +--- + +###### 32. Co zostanie wyświetlone w konsoli po kliknięciu akapitu? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Jeśli klikniemy `p`, zobaczymy dwa logi: `p` i `div`. Podczas propagacji zdarzeń istnieją 3 fazy: przechwytywanie, cel i bąbelkowanie (capturing, target, and bubbling). Domyślnie, event handlery są wykonywane w fazie bąbelkowania (chyba że ustawisz `useCapture` na `true`). Przebiega ona od najgłębiej zagnieżdżonego elementu na zewnątrz. + +

+
+ +--- + +###### 33. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Odpowiedź +

+ +#### Odpowiedź: D + +W obu przypadkach możemy przekazać obiekt, do którego ma się odnosić słowo kluczowe `this`. Jednakże, `.call` jest _wykonywane natychmiast_! + +`.bind.` zwraca _kopię_ funkcji, ale z powiązanym kontekstem! Nie jest ona wykonywana natychmiast. + +

+
+ +--- + +###### 34. Jaki jest wynik? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Funkcja `sayHi` zwraca zwróconą wartość natychmiast wywołanego wyrażenia funkcyjnego (IIFE). Ta funkcja zwróciła wartość `0`, która jest typu `"number"`. + +FYI: `typeof` może zwrócić następującą listę wartości: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` i `object`. Zauważ, że `typeof null` zwraca `"object"`. + +

+
+ +--- + +###### 35. Które z tych wartości są fałszywe? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Wszystkie są fałszywe + +
Odpowiedź +

+ +#### Odpowiedź: A + +Istnieje 8 fałszywych wartości: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (pusty ciąg) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Konstruktory funkcji, takie jak `new Number` i `new Boolean` są prawdziwe. + +

+
+ +--- + +###### 36. Jaki jest wynik? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`typeof 1` zwraca `"number"`. +`typeof "number"` zwraca `"string"`. + +

+
+ +--- + +###### 37. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Po ustawieniu wartości elementu w tablicy, która przekracza długość tablicy, JavaScript tworzy coś, co nazywa się "pustymi slotami". W rzeczywistości mają one wartość `undefined`, ale zobaczysz coś takiego jak: + +`[1, 2, 3, puste x 7, 11]`. + +w zależności od tego, gdzie go uruchomisz (jest inny dla każdej przeglądarki, node itp.). + +

+
+ +--- + +###### 38. Jaki jest wynik? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Blok `catch` otrzymuje argument `x`. Nie jest to ten sam `x` co zmienna, gdy przekazujemy argumenty. Ta zmienna `x` jest blokowa. + +Później, ustawiamy tę blokową zmienną równą `1` i ustawiamy wartość zmiennej `y`. Teraz wyświetlamy w konsoli zmienną blokową `x`, która jest równa `1`. + +Poza blokiem `catch`, `x` jest wciąż `undefined`, a `y` wynosi `2`. Gdy chcemy wykonać `console.log(x)` poza blokiem `catch`, zwraca on `undefined`, a `y` zwraca `2`. + +

+
+ +--- + +###### 39. Wszystko w JavaScript jest... + +- A: prymitywem lub obiektem +- B: funkcją lub obiektem +- C: podchwytliwe pytanie! tylko obiektem +- D: numerem lub obiektem + +
Odpowiedź +

+ +#### Odpowiedź: A + +JavaScript ma tylko prymitywne typy i obiekty. + +Typy prymitywne to `boolean`, `null`, `undefined`, `bigint`, `number`, `string` i `symbol`. + +To, co odróżnia prymityw od obiektu, to fakt, że prymitywy nie mają żadnych właściwości ani metod; zauważysz jednak, że `'foo'.toUpperCase()` wylicza `'FOO'` i nie powoduje `TypeError`. Dzieje się tak dlatego, że gdy próbujesz uzyskać dostęp do właściwości lub metody na prymitywie takim jak ciąg znaków, JavaScript niejawnie opakuje prymitywny typ za pomocą jednej z klas opakowujących, tj. `String`, a następnie natychmiast odrzuci opakowanie po ocenie wyrażenia. Wszystkie prymitywy z wyjątkiem `null` i `undefined` wykazują to zachowanie. + +

+
+ +--- + +###### 40. Jaki jest wynik? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`[1, 2]` jest naszą wartością początkową. Jest to wartość, z którą zaczynamy i wartość pierwszego `acc`.Podczas pierwszej rundy, `acc` to `[1, 2]`, a `cur` to `[0, 1]`.Łączymy je, co daje `[1, 2, 0, 1]`. + +Następnie `[1, 2, 0, 1]` to `acc`, a `[2, 3]` to `cur`. Łączymy je i otrzymujemy `[1, 2, 0, 1, 2, 3]`. + +

+
+ +--- + +###### 41. Jaki jest wynik? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`null` jest fałszywe. `!null` zwraca `true`. `!true` zwraca `false`. + +`""` jest fałszywe. `!""` zwraca `true`. `!true` zwraca `false`. + +`1` jest prawdziwe. `!1` zwraca `false`. `!false` zwraca `true`. + +

+
+ +--- + +###### 42. Co zwraca metoda `setInterval` w przeglądarce? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: unikalny identyfikator +- B: określona ilość milisekund +- C: przekazana funkcja +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Zwraca unikalny identyfikator. Ten identyfikator może być użyty do wyczyszczenia tego interwału za pomocą funkcji `clearInterval()`. + +

+
+ +--- + +###### 43. Co to zwróci? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Łańcuch znaków jest iterowalny. Operator spread odwzorowuje każdy znak iterable na jeden element. + +

+
+ +--- + +###### 44. Jaki jest wynik? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zwykłe funkcje nie mogą zostać zatrzymane w połowie wywoływania. Jednak funkcja generatora może zostać "zatrzymana" w połowie, a następnie kontynuować od miejsca, w którym się zatrzymała. Za każdym razem, gdy funkcja generująca napotka słowo kluczowe `yield`, funkcja zwraca wartość określoną po nim. + +Najpierw inicjalizujemy funkcję generatora z `i` równym `10`. Wywołujemy funkcję generatora za pomocą metody `next()`. Przy pierwszym wywołaniu funkcji generatora, `i` jest równe `10`. Funkcja napotyka pierwsze słowo kluczowe `yield`: zwraca wartość `i`. Generator jest teraz "wstrzymany", a wartość `10` zostaje zarejestrowana. + +Następnie ponownie wywołujemy funkcję za pomocą metody `next()`. Kontynuuje ona tam, gdzie zatrzymała się poprzednio, wciąż z `i` równym `10`. Teraz napotyka następne słowo kluczowe `yield` i zwraca `i * 2`. `i` jest równe `10`, więc zwraca `10 * 2`, czyli `20`. Wynikiem jest `10, 20`. + +

+
+ +--- + +###### 45. Co to zwróci? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Kiedy przekazujemy wiele 'promise' do metody `Promise.race`, rozwiązuje ona/odrzuca _pierwszą_ 'promise'. Do metody `setTimeout` przekazujemy timer: 500ms dla `firstPromise` i 100ms dla `secondPromise`. Oznacza to, że `secondPromise` zostanie rozwiązana jako pierwsza z wartością `'two'`. `res` przechowuje teraz wartość `'two'`, która jest wyświetlona w konsoli. + +

+
+ +--- + +###### 46. Jaki jest wynik? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Najpierw deklarujemy zmienną `person` z wartością obiektu, który ma właściwość `name`. + + + +Następnie deklarujemy zmienną o nazwie `members`. Ustawiamy pierwszy element tej tablicy równy wartości zmiennej `person`. Obiekty oddziałują na siebie poprzez _referencję_, gdy ustawiamy je równe sobie. Kiedy przypisujesz referencję z jednej zmiennej do drugiej, tworzysz _kopię_ tej referencji. (Zauważ, że nie mają one _tej samej_ referencji!). + + + +Następnie ustawiamy zmienną `person` równą `null`. + + + +Modyfikujemy tylko wartość zmiennej `person`, a nie pierwszy element w tablicy, ponieważ ten element ma inną (skopiowaną) referencję do obiektu. Pierwszy element w `members` wciąż posiada referencję do oryginalnego obiektu. Kiedy wyświetlamy tablicę `members`, pierwszy element nadal przechowuje wartość obiektu, który jest wyświetlany. + +

+
+ +--- + +###### 47. Jaki jest wynik? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą pętli `for-in` możemy iterować po kluczach obiektów, w tym przypadku `name` i `age`. Klucze obiektów są łańcuchami (jeśli nie są symbolami). W każdej pętli ustawiamy wartość `item` równą bieżącemu kluczowi, który iterujemy. Najpierw `item` jest równy `name`. Następnie, `item` jest równy `age`. + +

+
+ +--- + +###### 48. Jaki jest wynik? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Asocjatywność operatorów to kolejność, w jakiej kompilator ocenia wyrażenia, od lewej do prawej lub od prawej do lewej. Dzieje się tak tylko wtedy, gdy wszystkie operatory mają _takie samo_ pierwszeństwo. Mamy tylko jeden typ operatora: `+`. Dla dodawania, asocjatywność jest od lewej do prawej. + +`3 + 4` jest obliczane jako pierwsze. Wynikiem jest liczba `7`. + +`7 + '5'` skutkuje `"75"` z powodu przymusu. JavaScript konwertuje liczbę `7` na ciąg znaków, patrz pytanie 15. Możemy połączyć dwa ciągi znaków za pomocą operatora `+`. "7" + "5"` daje w wyniku "75"`. + +

+
+ +--- + +###### 49. Jaka jest wartość `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zwracana jest tylko pierwsza liczba w łańcuchu. W oparciu o _radix_ (drugi argument w celu określenia typu liczby, którą chcemy przetworzyć: podstawa 10, szesnastkowy, ósemkowy, binarny itp.), `parseInt` sprawdza, czy znaki w łańcuchu są prawidłowe. Gdy napotka znak, który nie jest prawidłową liczbą w radix, zatrzymuje parsowanie i ignoruje następujące znaki. + +`*` nie jest prawidłową liczbą. Przetwarza tylko `"7"` na dziesiętne `7`. `num` posiada teraz wartość `7`. + +

+
+ +--- + +###### 50. Jaki jest wynik? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Podczas mapowania tablicy, wartość `num` jest równa elementowi, nad którym aktualnie wykonywana jest pętla. W tym przypadku elementami są liczby, więc warunek instrukcji if `typeof num == "number"` zwraca `true`. Funkcja map tworzy nową tablicę i wstawia do niej wartości zwrócone przez funkcję. + +Nie zwracamy jednak żadnej wartości. Gdy nie zwracamy wartości z funkcji, funkcja zwraca `undefined`. Dla każdego elementu w tablicy wywoływany jest blok funkcji, więc dla każdego elementu zwracamy `undefined`. + +

+
+ +--- + +###### 51. Jaki jest wynik? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Argumenty są przekazywane przez _wartość_, chyba że ich wartość jest obiektem, wtedy są przekazywane przez _referencję_. Argument `birthYear` jest przekazywany przez wartość, ponieważ jest ciągiem znaków, a nie obiektem. Kiedy przekazujemy argumenty przez wartość, tworzona jest _kopia_ tej wartości (patrz pytanie 46). + +Zmienna `birthYear` posiada referencję do wartości `"1997"`. Argument `year` również posiada referencję do wartości `"1997"`, ale nie jest to ta sama wartość, do której odnosi się `birthYear`. Kiedy aktualizujemy wartość `year` ustawiając `year` na `"1998"`, aktualizujemy tylko wartość `year`. Wartość `birthYear` jest wciąż równa `1997`. + +Wartość `person` jest obiektem. Argument `member` posiada (skopiowaną) referencję do _tego samego_ obiektu. Gdy zmodyfikujemy właściwość obiektu, do którego odwołuje się `member`, wartość `person` również zostanie zmodyfikowana, ponieważ oba mają odwołanie do tego samego obiektu. Właściwość `name` obiektu `person` jest teraz równa wartości `"Lydia"`. + +

+
+ +--- + +###### 52. Jaki jest wynik? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Za pomocą instrukcji `throw` możemy tworzyć niestandardowe błędy. Za pomocą tej instrukcji można rzucać wyjątki string, number, boolean lub object. W tym przypadku, naszym wyjątkiem jest ciąg znaków `'Hello world!".` + +Za pomocą instrukcji `catch` możemy określić, co należy zrobić, jeśli wyjątek zostanie rzucony w bloku `try`. Wyjątkiem może być: string `'Hello world!'`. `e` jest teraz równe temu ciągowi, który wyświetlamy w konsoli. Skutkuje to `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Jaki jest wynik? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Kiedy zwracasz właściwość, wartość właściwości jest równa _zwróconej_ wartości, a nie wartości ustawionej w funkcji konstruktora. Zwracamy ciąg `"Maserati"`, więc `myCar.make` jest równe `"Maserati"`. + +

+
+ +--- + +###### 54. Jaki jest wynik? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +`let x = (y = 10);` jest w rzeczywistości skrótem od: + +```javascript +y = 10; +let x = y; +``` + +Kiedy ustawiamy `y` równe `10`, w rzeczywistości dodajemy właściwość `y` do globalnego obiektu (`window` w przeglądarce, `global` w Node). W przeglądarce, `window.y` jest teraz równe `10`. + +Następnie deklarujemy zmienną `x` z wartością `y`, która wynosi `10`. Zmienne zadeklarowane za pomocą słowa kluczowego `let` są _block scoped_ i są definiowane tylko w bloku, w którym zostały zadeklarowane; w tym przypadku natychmiast wywołane wyrażenie funkcji (IIFE). Kiedy używamy operatora `typeof`, operand `x` nie jest zdefiniowany: próbujemy uzyskać dostęp do `x` poza blokiem, w którym został zadeklarowany. Oznacza to, że `x` nie jest zdefiniowane. Wartości, które nie zostały przypisane lub zadeklarowane są typu "undefined". `console.log(typeof x)` zwraca `"undefined"`. + +Jednakże, utworzyliśmy globalną zmienną `y` podczas ustawiania `y` równego `10`. Wartość ta jest dostępna w dowolnym miejscu naszego kodu. Zmienna `y` jest zdefiniowana i przechowuje wartość typu `"number"`. `console.log(typeof y)` zwraca `"number"`. + +

+
+ +--- + +###### 55. Jaki jest wynik? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Możemy usuwać właściwości z obiektów za pomocą słowa kluczowego `delete`, również na prototypie. Usuwając właściwość z prototypu, nie jest ona już dostępna w łańcuchu prototypów. W tym przypadku funkcja `bark` nie jest już dostępna w prototypie po `delete Dog.prototype.bark`, a mimo to wciąż próbujemy uzyskać do niej dostęp. + +Kiedy próbujemy wywołać coś, co nie jest funkcją, rzucany jest `TypeError`. W tym przypadku `TypeError: pet.bark is not a function`, ponieważ `pet.bark` jest `undefined`. + +

+
+ +--- + +###### 56. Jaki jest wynik? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Odpowiedź +

+ +#### Odpowiedź: D + +Obiekt `Set` jest zbiorem _unikalnych_ wartości: wartość może wystąpić tylko raz w zbiorze. + +Przekazaliśmy iterowalne `[1, 1, 2, 3, 4]` ze zduplikowaną wartością `1`.Ponieważ nie możemy mieć dwóch takich samych wartości w zbiorze, jedna z nich jest usuwana. Wynikiem jest `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Jaki jest wynik? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Zaimportowany moduł jest _tylko do odczytu_: nie można modyfikować zaimportowanego modułu. Tylko moduł, który go eksportuje może zmienić jego wartość. + +Kiedy próbujemy zwiększyć wartość `myCounter`, wyrzuca błąd: `myCounter` jest tylko do odczytu i nie może być modyfikowany. + +

+
+ +--- + +###### 58. Jaki jest wynik? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator `delete` zwraca wartość logiczną: `true` po pomyślnym usunięciu, w przeciwnym razie zwróci `false`. Jednakże, zmienne zadeklarowane ze słowem kluczowym `var`, `const` lub `let` nie mogą być usunięte za pomocą operatora `delete`. + +Zmienna `name` została zadeklarowana ze słowem kluczowym `const`, więc jej usunięcie nie powiedzie się: Zwracane jest `false`. Kiedy ustawiliśmy wartość `age` równą `21`, w rzeczywistości dodaliśmy właściwość o nazwie `age` do obiektu globalnego. W ten sposób można pomyślnie usunąć właściwości z obiektów, również z obiektu globalnego, więc `delete age` zwraca `true`. + +

+
+ +--- + +###### 59. Jaki jest wynik? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Możemy rozpakować wartości z tablic lub właściwości z obiektów poprzez destrukturyzację. Na przykład: + +```javascript +[a, b] = [1, 2]; +``` + + + +Wartość `a` wynosi teraz `1`, a wartość `b` wynosi teraz `2`.To, co faktycznie zrobiliśmy w pytaniu, to: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Oznacza to, że wartość `y` jest równa pierwszej wartości w tablicy, którą jest liczba `1`.Kiedy logujemy `y`, zwracana jest wartość `1`. + +

+
+ +--- + +###### 60. Jaki jest wynik? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Możliwe jest łączenie obiektów za pomocą operatora rozprzestrzeniania `...`.Umożliwia on tworzenie kopii par klucz/wartość jednego obiektu i dodawanie ich do innego obiektu. W tym przypadku tworzymy kopie obiektu `user` i dodajemy je do obiektu `admin`. Obiekt `admin` zawiera teraz skopiowane pary klucz/wartość, czego wynikiem jest `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. Jaki jest wynik? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Za pomocą metody `defineProperty` możemy dodawać nowe właściwości do obiektu lub modyfikować istniejące. Kiedy dodajemy właściwość do obiektu za pomocą metody `defineProperty`, są one domyślnie _niewyliczalne_. Metoda `Object.keys` zwraca wszystkie _wyliczalne_ nazwy właściwości z obiektu, w tym przypadku tylko `"name"`. + +Właściwości dodane przy użyciu metody `defineProperty` są domyślnie niezmienne. Możesz nadpisać to zachowanie używając właściwości `writable`, `configurable` i `enumerable`. W ten sposób metoda `defineProperty` daje dużo większą kontrolę nad właściwościami dodawanymi do obiektu. + +

+
+ +--- + +###### 62. Jaki jest wynik? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Drugim argumentem `JSON.stringify` jest _replacer_. Zamiennik może być funkcją lub tablicą i pozwala kontrolować, co i w jaki sposób wartości powinny być łańcuchowane. + +Jeśli zamiennik jest _tablicą_, tylko nazwy właściwości zawarte w tablicy zostaną dodane do łańcucha JSON. W tym przypadku tylko właściwości o nazwach `"level"` i `"health"` są uwzględnione, `"username"` jest wykluczone. `data` jest teraz równa `"{"level":19, "health":90}"`. + +Jeśli zamiennik jest _funkcją_, funkcja ta jest wywoływana na każdej właściwości obiektu, który stringujesz. Wartość zwrócona z tej funkcji będzie wartością właściwości, gdy zostanie ona dodana do łańcucha JSON. Jeśli wartość jest `undefined`, właściwość ta zostanie wykluczona z łańcucha JSON. + +

+
+ +--- + +###### 63. Jaki jest wynik? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Operator jednoargumentowy `++` _najpierw zwraca_ wartość operandu, _potem zwiększa_ wartość operandu. Wartość `num1` to `10`, ponieważ funkcja `increaseNumber` najpierw zwraca wartość `num`, czyli `10`, a dopiero potem zwiększa wartość `num`. + +`num2` jest równe `10`, ponieważ przekazaliśmy `num1` do `increasePassedNumber`.`number` jest równe `10` (wartość `num1`). Ponownie, operator jednoargumentowy `++` _najpierw zwraca_ wartość operandu, _następnie zwiększa_ wartość operandu. Wartość `liczba` wynosi `10`, więc `liczba2` jest równa `10`. + +

+
+ +--- + +###### 64. Jaki jest wynik? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Odpowiedź +

+ +#### Odpowiedź: C + +W ES6 możemy inicjować parametry z wartością domyślną. Wartość parametru będzie wartością domyślną, jeśli żadna inna wartość nie została przekazana do funkcji lub jeśli wartość parametru jest `"undefined". W tym przypadku, rozkładamy właściwości obiektu `value` na nowy obiekt, więc `x` ma domyślną wartość `{ number: 10 }`. + +Domyślny argument jest obliczany w _call time_! Za każdym razem, gdy wywołujemy funkcję, tworzony jest _nowy_ obiekt. Wywołujemy funkcję `multiply` dwa pierwsze razy bez przekazywania wartości: `x` ma wartość domyślną `{ number: 10 }`. Następnie rejestrujemy pomnożoną wartość tej liczby, która wynosi `20`. + +Za trzecim razem, gdy wywołujemy multiply, przekazujemy argument: obiekt o nazwie `value`. Operator `*=` jest w rzeczywistości skrótem od `x.number = x.number * 2`: modyfikujemy wartość `x.number` i rejestrujemy pomnożoną wartość `20`. + +Za czwartym razem ponownie przekazujemy obiekt `value`. `x.number` zostało wcześniej zmodyfikowane do `20`, więc `x.number *= 2` loguje `40`. + +

+
+ +--- + +###### 65. Jaki jest wynik? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Odpowiedź +

s + +#### Odpowiedź: D + +Pierwszym argumentem, który otrzymuje metoda `reduce` jest _accumulator_, w tym przypadku `x`. Drugim argumentem jest _bieżąca wartość_, `y`. Za pomocą metody reduce wykonujemy funkcję wywołania zwrotnego na każdym elemencie tablicy, co ostatecznie może skutkować jedną wartością. W tym przykładzie nie zwracamy żadnych wartości, po prostu rejestrujemy wartości akumulatora i wartości bieżącej. + +Wartość akumulatora jest równa poprzednio zwróconej wartości funkcji zwrotnej. Jeśli nie przekażesz opcjonalnego argumentu `initialValue` do metody `reduce`, akumulator jest równy pierwszemu elementowi przy pierwszym wywołaniu. + +Przy pierwszym wywołaniu, wartość akumulatora (`x`) wynosi `1`, a wartość bieżąca (`y`) wynosi `2`. Nie wracamy z funkcji zwrotnej, rejestrujemy akumulator i bieżącą wartość: `1` i `2` są rejestrowane. + +Jeśli nie zwrócisz wartości z funkcji, zwróci ona `undefined`. Przy następnym wywołaniu, akumulatorem jest `undefined`, a bieżącą wartością jest `3`. `undefined` i `3` są rejestrowane. + +Przy czwartym wywołaniu ponownie nie wracamy z funkcji zwrotnej. Akumulator jest ponownie `undefined`, a aktualna wartość to `4`. `undefined` i `4` są rejestrowane. + +

+
+ +--- + +###### 66. Za pomocą którego konstruktora możemy z powodzeniem rozszerzyć klasę `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Odpowiedź +

+ +#### Odpowiedź: B + +W klasie pochodnej nie można uzyskać dostępu do słowa kluczowego `this` przed wywołaniem `super`. Jeśli spróbujesz to zrobić, zostanie wyświetlony ReferenceError: 1 i 4 wyrzuci błąd referencji. + +Za pomocą słowa kluczowego `super` wywołujemy konstruktor klasy nadrzędnej z podanymi argumentami. Konstruktor rodzica otrzymuje argument `name`, więc musimy przekazać `name` do `super`. + +Klasa `Labrador` otrzymuje dwa argumenty, `name` ponieważ rozszerza klasę `Dog`, oraz `size` jako dodatkową właściwość klasy `Labrador`. Oba muszą być przekazane do funkcji konstruktora na `Labrador`, co jest zrobione poprawnie przy użyciu konstruktora 2. + +

+
+ +--- + +###### 67. Jaki jest wynik? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Ze słowem kluczowym `import`, wszystkie zaimportowane moduły są _pre-parsed_. Oznacza to, że zaimportowane moduły są uruchamiane _najpierw_, a kod w pliku, który importuje moduł jest wykonywany _potem_. + +Jest to różnica pomiędzy `require()` w CommonJS i `import`! +Dzięki `require()` można ładować zależności na żądanie podczas wykonywania kodu. Jeśli użylibyśmy `require` zamiast `import`, w konsoli zostałoby wyświetlone `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Jaki jest wynik? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Odpowiedź +

+ +#### Odpowiedź: A + +Każdy Symbol jest całkowicie unikalny. Celem argumentu przekazywanego do Symbolu jest nadanie Symbolowi opisu. Wartość Symbolu nie zależy od przekazanego argumentu. Testując równość, tworzymy dwa zupełnie nowe symbole: pierwszy `Symbol('foo')` i drugi `Symbol('foo')`. Te dwie wartości są unikalne i nie są sobie równe, `Symbol('foo') == Symbol('foo')` zwraca `false`. + +

+
+ +--- + +###### 69. Jaki jest wynik? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Odpowiedź +

+ +#### Odpowiedź: C + +Za pomocą metody `padStart` możemy dodać dopełnienie na początku ciągu znaków. Wartością przekazywaną do tej metody jest _całkowita_ długość łańcucha wraz z dopełnieniem. Ciąg `"Lydia Hallie"` ma długość `12`. Metoda `name.padStart(13)` wstawia 1 spację na początku łańcucha, ponieważ 12 + 1 to 13. + +Jeśli argument przekazany do metody `padStart` jest mniejszy niż długość tablicy, dopełnienie nie zostanie dodane. + +

+
+ +--- + +###### 70. Jaki jest wynik? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Odpowiedź +

+ +#### Odpowiedź: A + +Za pomocą operatora `+` można łączyć ciągi znaków. W tym przypadku łączymy ciąg `"🥑"` z ciągiem `"💻"`, otrzymując `"🥑💻"`. + +

+
+ +--- + +###### 71. Jak możemy rejestrować wartości, które są komentowane po instrukcji console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` and `game.next().value` +- B: `game.next.value("Yes")` and `game.next.value()` +- C: `game.next().value` and `game.next("Yes").value` +- D: `game.next.value()` and `game.next.value("Yes")` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Funkcja generatora "wstrzymuje" swoje wykonanie, gdy widzi słowo kluczowe `yield`. Najpierw musimy pozwolić funkcji na wygenerowanie ciągu "Do you love JavaScript?", co można zrobić poprzez wywołanie `game.next().value`. + +Każda linia jest wykonywana, dopóki nie znajdzie pierwszego słowa kluczowego `yield`. W pierwszej linii funkcji znajduje się słowo kluczowe `yield`: wykonywanie zatrzymuje się wraz z pierwszym yield! Oznacza to, że zmienna `answer` nie jest jeszcze zdefiniowana! + +Kiedy wywołamy `game.next("Yes").value`, poprzedni `yield` zostanie zastąpiony wartością parametrów przekazanych do funkcji `next()`, w tym przypadku `"Yes``. Wartość zmiennej `answer` jest teraz równa `"Yes"`. Warunek instrukcji if zwraca `false`, a `JavaScript loves you back ❤️` zostaje zalogowany. + +

+
+ +--- + +###### 72. Jaki jest wynik? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Odpowiedź +

+ +#### Odpowiedź: C + +`String.raw` zwraca ciąg znaków, w którym znaki specjalne (`\n`, `\v`, `\t` itd.) są ignorowane! Backslashe mogą być problemem, ponieważ można skończyć z czymś takim jak:`` const path = `C:\Documents\Projects\table.html` `` + +Co skutkowałoby: + +`"C:DocumentsProjects able.html"`Z `String.raw`, po prostu zignorowałby ucieczkę i wyświetliłby: + +`C:\Documents\Projects\table.html`. + +W tym przypadku ciąg to `Hello\nworld`, który zostanie wyświetlony. + +

+
+ +--- + +###### 73. Jaki jest wynik? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: C + +Funkcja asynchroniczna zawsze zwraca obietnicę. Funkcja `await` wciąż musi czekać na rozwiązanie obietnicy: oczekująca obietnica zostanie zwrócona, gdy wywołamy `getData()` w celu ustawienia `data` równym tej obietnicy. + +Jeśli chcielibyśmy uzyskać dostęp do rozwiązanej wartości `"I made it"`, moglibyśmy użyć metody `.then()` na `data`:`data.then(res => console.log(res))`. + +To wyświtliłoby w konsoli `"Udało mi się!"`. + +

+
+ +--- + +###### 74. Jaki jest wynik? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Odpowiedź +

+ +#### Odpowiedź: B + +Metoda `.push()` zwraca _długość_ nowej tablicy! Poprzednio tablica zawierała jeden element (string `"banan"`) i miała długość `1`. Po dodaniu stringa `"apple"` do tablicy, tablica zawiera dwa elementy i ma długość `2`. Jest to zwracane przez funkcję `addToList`. Metoda `push` modyfikuje oryginalną tablicę. + +Jeśli chciałeś zwrócić _array_ z funkcji, a nie _length of the array_, powinieneś był zwrócić `list` po dodaniu do niej `item`. + +

+
+ +--- + +###### 75. Jaki jest wynik? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Odpowiedź +

+ +#### Odpowiedź: B + +`Object.freeze` uniemożliwia dodawanie, usuwanie lub modyfikowanie właściwości obiektu (chyba że wartością właściwości jest inny obiekt). + +Kiedy tworzymy zmienną `shape` i ustawiamy ją jako równą zamrożonemu obiektowi `box`, `shape` również odnosi się do zamrożonego obiektu. Możesz sprawdzić czy obiekt jest zamrożony używając `Object.isFrozen`. W tym przypadku, `Object.isFrozen(shape)` zwróciłby true, ponieważ zmienna `shape` posiada referencję do zamrożonego obiektu. + +Ponieważ `shape` jest zamrożony, a wartość `x` nie jest obiektem, nie możemy modyfikować właściwości `x`.`x` jest nadal równe `10`, a `{ x: 10, y: 20 }` zostaje wyświetlone w konsoli. + +

+
\ No newline at end of file diff --git a/pt-BR/README_pt_BR.md b/pt-BR/README_pt_BR.md index e53887dc..54c8daf1 100644 --- a/pt-BR/README_pt_BR.md +++ b/pt-BR/README_pt_BR.md @@ -6,28 +6,33 @@ Do básico ao avançado: Teste quão bem você conhece o JavaScript, refresque u As respostas estão em seções recolhidas abaixo das questões, basta clicar nelas para expandir. Boa sorte :heart: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- -###### 1. Qual é a saída? +###### 1. Qual o resultado? ```javascript function sayHi() { @@ -52,14 +57,14 @@ sayHi(); Dentro da função, nós primeiro declaramos a variável `name` usando a palavra-chave `var`. Isso significa que a variavel é elevada(hoisted) (O espaço na memória é separado durante a fase de criação) com o valor padrão `undefined`, até que chegue na linha onde definimos a variável. Ainda não definimos a variável na linha onde tentamos usar colocar no log o valor da variável `name`, portanto ela ainda tem o valor `undefined`. -Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de `var`, não são inicializadas. Elas não acessíveis antes da linha em que as declaramos (ou inicializamos). Esse é um conceito chamado de "temporal dead zone". Quando tentamos acessar essas variáveis antes de serem declaradas, o JavaScript lança um `ReferenceError` +Variáveis com a palavra-chave `let` (e `const`) são elevadas, mas diferente de `var`, não são inicializadas. Elas não estão acessíveis antes da linha em que as declaramos (ou inicializamos). Esse é um conceito chamado de "temporal dead zone". Quando tentamos acessar essas variáveis antes de serem declaradas, o JavaScript lança um `ReferenceError`.

--- -###### 2. Qual é a saída? +###### 2. Qual o resultado? ```javascript for (var i = 0; i < 3; i++) { @@ -89,7 +94,7 @@ No segundo laço, a variável `i` foi declarada usando a palavra-chave `let`: Va --- -###### 3. Qual é a saída? +###### 3. Qual o resultado? ```javascript const shape = { @@ -125,7 +130,7 @@ Não há `radius` fora de shape, então retorna `undefined`. --- -###### 4. Qual é a saída? +###### 4. Qual o resultado? ```javascript +true; @@ -187,7 +192,7 @@ Por outro lado, com a notação de ponto `.`, isso não acontece. `mouse` não t --- -###### 6. Qual é a saída? +###### 6. Qual o resultado? ```javascript let c = { greeting: "Hey!" }; @@ -222,7 +227,7 @@ Quando você muda um objeto, você muda todos eles. --- -###### 7. Qual é a saída? +###### 7. Qual o resultado? ```javascript let a = 3; @@ -255,7 +260,7 @@ Contudo, quando usamos o operador `===`, ambos valor e tipo tem de ser o --- -###### 8. Qual é a saída? +###### 8. Qual o resultado? ```javascript class Chameleon { @@ -291,7 +296,7 @@ Já que `freddie` é filho de `Chameleon`, a função não é herdada, e não es --- -###### 9. Qual é a saída? +###### 9. Qual o resultado? ```javascript let greeting; @@ -346,7 +351,7 @@ Uma função é um tipo especial de objeto. O código que você escreve não é --- -###### 11. Qual é a saída? +###### 11. Qual o resultado? ```javascript function Person(firstName, lastName) { @@ -389,7 +394,7 @@ faria `member.getFullName()` funcionar. Por quê isso é beneficial? Digamos que --- -###### 12. Qual é a saída? +###### 12. Qual o resultado? ```javascript function Person(firstName, lastName) { @@ -462,7 +467,7 @@ Todos objetos tem protótipos, exceto pelo **base object**. O base object tem ac --- -###### 15. Qual é a saída? +###### 15. Qual o resultado? ```javascript function sum(a, b) { @@ -491,7 +496,7 @@ Nesse exemplo, JavaScript converte o número `1` em uma string, para que a funç --- -###### 16. Qual é a saída? +###### 16. Qual o resultado? ```javascript let number = 0; @@ -527,7 +532,7 @@ Isso retorna `0 2 2`. --- -###### 17. Qual é a saída? +###### 17. Qual o resultado? ```javascript function getPersonInfo(one, two, three) { @@ -558,7 +563,7 @@ Se usamos template literals marcadas, ou tagged template literals, o valor do pr --- -###### 18. Qual é a saída? +###### 18. Qual o resultado? ```javascript function checkAge(data) { @@ -594,7 +599,7 @@ Os dois objetos que estamos comparando não são assim: O objeto que passamos co --- -###### 19. Qual é a saída? +###### 19. Qual o resultado? ```javascript function getAge(...args) { @@ -614,14 +619,14 @@ getAge(21); #### Resposta: C -O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é um objeto, então `typeof args` retorna `"object"` +O operador _spread_ (`...args`.) retorna um array com os argumentos. Um array é um objeto, então `typeof args` retorna `"object"`.

--- -###### 20. Qual é a saída? +###### 20. Qual o resultado? ```javascript function getAge() { @@ -666,7 +671,7 @@ const sum = eval("10*10+5"); #### Resposta: A -`eval` executa o código mesmo se passado como string. Se é uma expressão, como nesse caso, ele cálcula a expressão. A expressão é `10 * 10 + 5`. Isso retorna o número `105`. +`eval` executa o código mesmo se passado como string. Se é uma expressão, como nesse caso, ele calcula a expressão. A expressão é `10 * 10 + 5`. Isso retorna o número `105`.

@@ -698,7 +703,7 @@ Se usássemos `localStorage`, o dado seria guardado para sempre, exceto se `loca --- -###### 23. Qual é a saída? +###### 23. Qual o resultado? ```javascript var num = 8; @@ -726,7 +731,7 @@ Você não pode fazer isso com `let` ou `const` uma vez que eles conferem o bloc --- -###### 24. Qual é a saída? +###### 24. Qual o resultado? ```javascript const obj = { 1: "a", 2: "b", 3: "c" }; @@ -757,7 +762,7 @@ Não funciona assim para `Set`. Não tem um `'1'` no nosso set: `set.has('1')` r --- -###### 25. Qual é a saída? +###### 25. Qual o resultado? ```javascript const obj = { a: "one", b: "two", a: "three" }; @@ -799,7 +804,7 @@ O contexto base de execução é o contexto global: É aquilo que está acessív --- -###### 27. Qual é a saída? +###### 27. Qual o resultado? ```javascript for (let i = 1; i < 5; i++) { @@ -825,7 +830,7 @@ A palavra-chave `continue` pula uma iteração se a condição retorna `true`. --- -###### 28. Qual é a saída? +###### 28. Qual o resultado? ```javascript String.prototype.giveLydiaPizza = () => { @@ -834,7 +839,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -854,7 +859,7 @@ name.giveLydiaPizza(); --- -###### 29. Qual é a saída? +###### 29. Qual o resultado? ```javascript const a = {}; @@ -888,7 +893,7 @@ Então, fazemos o log de `a[b]`, o que na verdade é `a["object Object"]`. Acabm --- -###### 30. Qual é a saída? +###### 30. Qual o resultado? ```javascript const foo = () => console.log("First"); @@ -997,7 +1002,7 @@ Se clicarmos em `p`, veremos dois itens adicionaos ao log: `p` e `div`. Durante --- -###### 33. Qual é a saída? +###### 33. Qual o resultado? ```javascript const person = { name: "Lydia" }; @@ -1029,7 +1034,7 @@ Com ambos, podemos passar o objeto que queremos que o `this` faça referência. --- -###### 34. Qual é a saída? +###### 34. Qual o resultado? ```javascript function sayHi() { @@ -1051,7 +1056,7 @@ typeof sayHi(); A função `sayHi` retorna o valor retornado pela arrow function pois ela é uma IIFE (Immediately Invoked Function Expression ou Expressão de Função Invocada Imediatamente). Essa IIFE retornou `0`, que é do tipo `"number"`. -Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, e `symbol`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`. +Para saber mais: Só existem 7 tipos já definidos: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, e `bigint`. `"function"` não é um tipo, uma vez que funções são objetos, elas são do tipo `"object"`.

@@ -1095,7 +1100,7 @@ Funções construtoras, como `new Number` e `new Boolean` são truthy. --- -###### 36. Qual é a sáida? +###### 36. Qual é a saída? ```javascript console.log(typeof typeof 1); @@ -1119,7 +1124,7 @@ console.log(typeof typeof 1); --- -###### 37. Qual é a saída? +###### 37. Qual o resultado? ```javascript const numbers = [1, 2, 3]; @@ -1148,7 +1153,7 @@ dependendo de onde você o executa, pois é diferente para cada navegador, node --- -###### 38. Qual é a saída? +###### 38. Qual o resultado? ```javascript (() => { @@ -1201,14 +1206,14 @@ JavaScript tem somente tipos primitivos e objetos. Tipos primitivos são `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, e `symbol`. -O que diferencia um primitivo de um objeto é que primitivos não métodos ou propriedades. Contudo, se você está atento vai lembrar que `'foo'.toUpperCase()` retorna `'FOO'` e não resulta em um `TypeError`. Isso acontece pois quando você tenta acessar uma propriedade ou método em um primitivo como, por exemplo, uma string, JavaScript vai transformar esse primitivo em objeto usando um _wrapper_, nesse caso o `String`, e discarta o wrapper imediatamente após executar o método ou propriedade. Todos os primitivos, com exceção de `null` e `undefined` exibem esse comportamento. +O que diferencia um primitivo de um objeto é que primitivos não possuem métodos ou propriedades. Contudo, se você está atento vai lembrar que `'foo'.toUpperCase()` retorna `'FOO'` e não resulta em um `TypeError`. Isso acontece pois quando você tenta acessar uma propriedade ou método em um primitivo como, por exemplo, uma string, JavaScript vai transformar esse primitivo em objeto usando um _wrapper_, nesse caso o `String`, e discarta o wrapper imediatamente após executar o método ou propriedade. Todos os primitivos, com exceção de `null` e `undefined` exibem esse comportamento.

--- -###### 40. Qual é a saída? +###### 40. Qual o resultado? ```javascript [[0, 1], [2, 3]].reduce( @@ -1238,7 +1243,7 @@ Então, `[1, 2, 0, 1]` é `acc` e `[2, 3]` é o `cur`. Concatenamos novamente, e --- -###### 41. Qual é a saída? +###### 41. Qual o resultado? ```javascript !!null; @@ -1313,7 +1318,7 @@ Strings são iteráveis. O operador do spread `...` mapeia todo caractére de um --- -###### 44. Qual é a saída? +###### 44. Qual o resultado? ```javascript function* generator(i) { @@ -1378,7 +1383,7 @@ Quando passamos múltiplas "promises" para a função `Promise.race`, ele resolv --- -###### 46. Qual é a saída? +###### 46. Qual o resultado? ```javascript let person = { name: "Lydia" }; @@ -1417,7 +1422,7 @@ Estamos apenas modificando o valor da variável `person`, e não o primeiro elem --- -###### 47. Qual é a saída? +###### 47. Qual o resultado? ```javascript const person = { @@ -1447,7 +1452,7 @@ Utilizando o loop `for-in`, podemos interar através das chaves do objeto, neste --- -###### 48. Qual é a saída? +###### 48. Qual o resultado? ```javascript console.log(3 + 4 + "5"); @@ -1499,7 +1504,7 @@ Apenas os primeiros números da string é retornado. Baseado no _radix_ (o segun --- -###### 50. Qual é a saída? +###### 50. Qual o resultado? ```javascript [1, 2, 3].map(num => { @@ -1527,7 +1532,7 @@ Entretanto, não se retorna o valor. Quando não se retorna um valor para a fun --- -###### 51. Qual é a saída? +###### 51. Qual o resultado? ```javascript function getInfo(member, year) { @@ -1561,7 +1566,7 @@ O valor de `person` é um objeto. O argumento `member` possui uma referência (c --- -###### 52. Qual é a saída? +###### 52. Qual o resultado? ```javascript function greeting() { @@ -1597,7 +1602,7 @@ Com a declaração `catch`, podemos especificar o que fazer se uma exceção for --- -###### 53. Qual é a saída? +###### 53. Qual o resultado? ```javascript function Car() { @@ -1625,7 +1630,7 @@ Quando você retorna uma propriedade, o valor da propriedade é igual ao valor _ --- -###### 54. Qual é a saída? +###### 54. Qual o resultado? ```javascript (() => { @@ -1663,7 +1668,7 @@ No entanto, criamos uma variável global `y` ao definir `y` igual a `10`. Este v --- -###### 55. Qual é a saída? +###### 55. Qual o resultado? ```javascript class Dog { @@ -1699,7 +1704,7 @@ Quando tentamos invocar algo que não é uma função, um `TypeError` é lançad --- -###### 56. Qual é a saída? +###### 56. Qual o resultado? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1725,7 +1730,7 @@ Passamos o iterável `[1, 1, 2, 3, 4]` com um valor `1` duplicado. Como não pod --- -###### 57. Qual é a saída? +###### 57. Qual o resultado? ```javascript // counter.js @@ -1759,7 +1764,7 @@ Quando tentamos aumentar o valor de `myCounter`, recebemos um erro: `myCounter` --- -###### 58. Qual é a saída? +###### 58. Qual o resultado? ```javascript const name = "Lydia"; @@ -1787,7 +1792,7 @@ A variável `name` foi declarada com `const`, portanto sua exclusão não é bem --- -###### 59. Qual é a saída? +###### 59. Qual o resultado? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1828,7 +1833,7 @@ Isso significa que o valor de `y` é igual ao primeiro valor no array, que é o --- -###### 60. Qual é a saída? +###### 60. Qual o resultado? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1883,7 +1888,7 @@ Assim, o método `defineProperty` dá a você muito mais controle sobre as propr --- -###### 62. Qual é a saída? +###### 62. Qual o resultado? ```javascript const settings = { @@ -1904,7 +1909,7 @@ console.log(data);
Resposta

-#### Answer: A +#### Resposta: A O segundo argumento de `JSON.stringify` é o _substituo_. O substituto pode ser uma função ou um array, e deixa você controlar o que deve ser "stringfied", isto é, ser usado pelo método `JSON.stringfy`. @@ -1915,3 +1920,593 @@ Se o substituto (replacer) for uma _função_, essa função é chamada em c ada

--- +###### 63. Qual o resultado? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Resposta +

+ +#### Resposta: A + +O operador unário `++` primeiro _retorna_ o valor do operando, depois _incrementa_ esse valor. O valor de `num1` é `10`, pois a função `increaseNumber` retorna primeiro o valor de` num`, que é `10`, e apenas incrementa o valor de `num` posteriormente. + +`num2` é `10`, já que passamos `num1` para o `increasePassedNumber`. `number` é igual a` 10` (o valor de `num1`. Novamente, o operador unário `++` primeiro _retorna_ o valor do operando, depois _aumenta_ esse valor. O valor de` number` é `10`, então `num2` é igual a `10`. + +

+
+ +--- +###### 64. Qual o resultado? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Resposta +

+ +#### Resposta: C + +No ES6, podemos inicializar parâmetros com um valor padrão. O valor do parâmetro será o valor padrão, se nenhum outro valor tiver sido passado para a função ou se o valor do parâmetro for `"undefined"`. Nesse caso, espalhamos (spread) as propriedades do objeto `value` para um novo objeto, para que `x` tenha o valor padrão de `{number: 10}`. + +O argumento padrão é executado _a cada chamada_! Toda vez que chamamos a função, um _novo_ objeto é criado. Invocamos a função `multiply` as duas primeiras vezes sem passar um valor: `x` tem o valor padrão de `{number: 10}`. Em seguida, registramos (log) o valor multiplicado desse número, que é `20`. + +Na terceira vez que invocamos multiply, passamos um argumento: o objeto chamado `value`. O operador `*=` é na verdade uma abreviação de `x.number = x.number * 2`: modificamos o valor de `x.number` e registramos (log) o valor multiplicado `20`. + +Na quarta vez, passamos o objeto `value` novamente. `x.number` foi modificado anteriormente para `20`, então `x.number *= 2` registra `40`. + +

+
+ +--- +###### 65. Qual o resultado? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
Resposta +

+ +#### Resposta: D + +O primeiro argumento que o método `reduce` recebe é o _acumulador_, `x` neste caso. O segundo argumento é o _valor atual_, `y`. Com o método `reduce`, executamos uma função de retorno de chamada (callback function) em todos os elementos da matriz, o que pode resultar em um único valor. + +Neste exemplo, não estamos retornando nenhum valor, estamos simplesmente registrando os valores do acumulador e o valor atual. + +O valor do acumulador é igual ao valor retornado anteriormente da função de retorno de chamada (callback function). Se você não passar o argumento opcional `initialValue` para o método `reduce`, o acumulador será igual ao primeiro elemento na primeira chamada. + +Na primeira chamada, o acumulador (`x`) é `1` e o valor atual (`y`) é `2`. Não retornamos da função de retorno de chamada, registramos o acumulador e o valor atual: `1` e` 2` são registrados. + +Se você não retornar um valor de uma função, ele retornará `undefined`. Na próxima chamada, o acumulador é "undefined" e o valor atual é "3". `undefined` e `3` são registrados. + +Na quarta chamada, novamente não retornamos nada da função de retorno de chamada. O acumulador é novamente `undefined` e o valor atual é `4`. `undefined` e `4` são registrados. + +

+
+ +--- +###### 66. Com qual construtor podemos estender com sucesso a classe `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Resposta +

+ +#### Resposta: B + +Em uma classe derivada, você não pode acessar a palavra-chave `this` antes de chamar `super`. Se você tentar fazer isso, ele lançará um erro de referência (ReferenceError): 1 e 4 lançará um erro de referência. + +Com a palavra-chave `super`, chamamos o construtor dessa classe pai com os argumentos fornecidos. O construtor do pai recebe o argumento `name`, portanto, precisamos passar `name` para `super`. + +A classe `Labrador` recebe dois argumentos, `name`, pois estende `Dog`, e `size` como uma propriedade extra na classe `Labrador`. Ambos precisam ser passados para a função construtora no `Labrador`, que é feita corretamente usando o construtor 2. + +

+
+ +--- +###### 67. Qual o resultado? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Resposta +

+ +#### Resposta: B + +Com a palavra-chave `import`, todos os módulos importados são _pre-parsed_. Isso significa que os módulos importados são executados _primeiro_, o código no arquivo que importa o módulo é executado _depois_. + +Esta é uma diferença entre `require()` no CommonJS e `import`! Com `require()`, você pode carregar dependências sob demanda enquanto o código está sendo executado. Se tivéssemos usado `require` em vez de `import`, `running index.js`,` running sum.js`, `3` teriam sido registrados no console. + +

+
+ +--- +###### 68. Qual o resultado? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Resposta +

+ +#### Resposta: A + +Todo símbolo (Symbol) é totalmente único. O objetivo do argumento passado ao símbolo é fornecer uma descrição ao símbolo. O valor do símbolo não depende do argumento passado. Ao testarmos a igualdade, estamos criando dois símbolos totalmente novos: o primeiro `Symbol('foo')` e o segundo `Symbol('foo')`. Esses dois valores são únicos e não são iguais entre si, `Symbol('foo') === Symbol('foo')` retorna `false`. + +

+
+ +--- +###### 69. Qual o resultado? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Resposta +

+ +#### Resposta: C + +Com o método `padStart`, podemos adicionar preenchimento (padding) ao início de uma string. O valor passado para esse método é o comprimento _total_ da string junto com o preenchimento. A string `"Lydia Hallie"` tem um comprimento de `12`. `name.padStart(13)` insere 1 espaço no início da string, porque 12 + 1 é 13. + +Se o argumento passado para o método `padStart` for menor que o comprimento da matriz, nenhum preenchimento será adicionado. + +

+
+ +--- +###### 70. Qual o resultado? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: A string containing their code points +- D: Error + +
Resposta +

+ +#### Resposta: A + +Com o operador `+`, você pode concatenar seqüências de caracteres (strings). Neste caso, estamos concatenando a string `"🥑"` com a string `"💻"`, resultando em `"🥑💻"`. + +

+
+ +--- + +###### 71. Como podemos registrar os valores comentados após a instrução console.log? + +```javascript +function* iniciarJogo() { + const resposta = yield 'Você ama JavaScript?'; + if (resposta !== 'Sim') { + return "Uau... Acho que entramos aqui"; + } + return 'O JavaScript também ama você ❤️'; +} + +const jogo = iniciarJogo(); +console.log(/* 1 */); // Você ama JavaScript? +console.log(/* 2 */); // O JavaScript também ama você ❤️ +``` + +- A: `jogo.next("Sim").value` and `jogo.next().value` +- B: `jogo.next.value("Sim")` and `jogo.next.value()` +- C: `jogo.next().value` and `jogo.next("Sim").value` +- D: `jogo.next.value()` and `jogo.next.value("Sim")` + +
Resposta +

+ +#### Resposta: C + +Uma função geradora "pausa" a sua execução quando encontra a palavra-chave `yield`. Primeiro, temos que deixar a função produzir a string "Você ama JavaScript?", o que pode ser feito chamando `jogo.next().value`. + +Cada linha é executada, até encontrar a primeira palavra-chave `yield`. Há uma palavra-chave `yield` na primeira linha da função: a execução para com o primeiro retorno! _Isso significa que a variável `resposta` ainda não foi definida!_ + +Quando chamamos `jogo.next("Sim").value`, o `yield` anterior é substituído pelo valor dos parâmetros passados para a função `next()`, `"Sim"` neste caso. O valor da variável `"resposta"` agora é igual a `"Sim"`. A condição da instrução if retorna `false` e `JavaScript também ama você ❤️` é registrada. + +

+
+ +--- + +###### 72. Qual é o resultado? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Answer +

+ +#### Answer: C + +`String.raw` retorna um texto onde os escape (`\n`, `\v`, `\t` etc.) são ignorados! As barras invertidas podem ser um problema, pois você pode acabar com algo como: + +`` caminho const = `C:\Documents\Projects\table.html` `` + +O que resultaria em: + +`"C:DocumentsProjectstable.html"` + +Com `String.raw`, ele simplesmente ignoraria o escape e imprimiria: + +`C:\Documents\Projects\table.html` + +Neste caso, a string é `Hello\nworld`, que é registrada. + +

+
+ +--- +###### 73. Qual o resultado? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Answer +

+ +#### Resposta: C + +Uma função assíncrona sempre retorna uma promise. O `await` ainda tem que esperar que a promise seja resolvida: uma promise pendente é retornada quando chamamos `getData()` para definir `data` igual a ela. + +Se quiséssemos ter acesso ao valor resolvido `"I made it"`, poderíamos ter usado o método `.then()` em `data`: + +`data.then(res => console.log(res))` + +Isso teria registrado `"Consegui!"` + +

+
+ +--- +###### 74. Qual o resultado? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Answer +

+ +#### Answer: B + +O método `.push()` retorna o _length_ do novo array! Anteriormente, a matriz continha um elemento (a string `"banana"`) e tinha um comprimento de `1`. Depois de adicionar a string `"apple"` ao array, o array contém dois elementos e tem um comprimento de `2`. Isso é retornado da função `addToList`. + +O método `push` modifica o array original. Se você quisesse retornar o _array_ da função ao invés do _tamanho do array_, você deveria ter retornado `list` depois de enviar `item` para ele. + +

+
+ +--- + +###### 75. Qual o resultado? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: B + +`Object.freeze` torna impossível adicionar, remover ou modificar propriedades de um objeto (a menos que o valor da propriedade seja outro objeto). + +Quando criamos a variável `shape` e a definimos igual ao objeto congelado `box`, `shape` também se refere a um objeto congelado. Você pode verificar se um objeto está congelado usando `Object.isFrozen`. Neste caso, `Object.isFrozen(shape)` retorna true, pois a variável `shape` tem uma referência a um objeto congelado. + +Como `shape` está congelado, e como o valor de `x` não é um objeto, não podemos modificar a propriedade `x`. `x` ainda é igual a `10`, e `{ x: 10, y: 20 }` é registrado. + +

+
+ +--- + +###### 76.Qual o resultado? + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(name); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Answer +

+ +#### Answer: D + +Quando descompactamos a propriedade `name` do objeto do lado direito, atribuímos seu valor `"Lydia"` a uma variável com o nome `myName`. + +Com `{ name: myName }`, informamos ao JavaScript que queremos criar uma nova variável chamada `myName` com o valor da propriedade `name` no lado direito. + +Quando tentamos mostrar o conteúdo de `name`, uma variável que não está definida, recebemos o erro `ReferenceError`. + +

+
+ +--- + +###### 77. É uma função pura? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Sim +- B: Não + +
Answer +

+ +#### Answer: A + +Uma função pura é uma função que _sempre_ retorna o mesmo resultado, se os mesmos argumentos forem passados. + +A função `sum` sempre retorna o mesmo resultado. Se passarmos `1` e` 2`, ele _sempre_ retornará `3` sem efeitos colaterais. Se passarmos `5` e `10`, ele _sempre_ retornará `15`, e assim por diante. Esta é a definição de uma função pura. + +

+
+ +--- + +###### 78. Qual o resultado? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Answer +

+ +#### Answer: C + +A função `add` é uma função _memoized_ (memorizada). Com a memorização, podemos armazenar em cache os resultados de uma função para acelerar sua execução. Nesse caso, criamos um objeto `cache` que armazena os valores retornados anteriormente. + +Se chamarmos a função `addFunction` novamente com o mesmo argumento, ela primeiro verifica se já obteve esse valor em seu cache. Se for o caso, o valor dos caches será retornado, o que economiza tempo de execução. Caso contrário, se não estiver armazenado em cache, ele calculará o valor e o armazenará posteriormente. + +Chamamos a função `addFunction` três vezes com o mesmo valor: na primeira chamada, o valor da função quando `num` é igual a `10` ainda não é armazenado em cache. A condição da instrução if `num in cache` retorna `false`, e o bloco else é executado: `Calculated! 20` é registrado e o valor do resultado é adicionado ao objeto de cache. `cache` agora se parece com` {10:20} `. + +Na segunda vez, o objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. + +Na terceira vez, passamos `5 * 2` para a função que é avaliada como `10`. O objeto `cache` contém o valor que é retornado para `10`. A condição da instrução if `num in cache` retorna `true`, e `'From cache! 20'` é registrado. + +

+
+ +--- + +###### 79. Qual o resultado? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` and `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Answer +

+ +#### Answer: A + +Com um loop _for-in_, podemos iterar sobre propriedades **enumeráveis​​**. Em um array, as propriedades enumeráveis ​​são as "chaves" dos elementos do array, que na verdade são seus índices. Você pode ver uma matriz como: + +`{0:" ☕ ", 1:" 💻 ", 2:" 🍷 ", 3:" 🍫 "}` + +Onde as chaves são as propriedades enumeráveis. `0`` 1` `2`` 3` são registrados. + +Com um loop _for-of_, podemos iterar sobre **iteráveis**. Um array é um iterável. Quando iteramos sobre o array, a variável "item" é igual ao elemento sobre o qual está iterando no momento, `" ☕ "` `" 💻 "` `" 🍷 "` `" 🍫 "` são registrados. + +

+
+ +--- + +###### 80. Qual o resultado? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Answer +

+ +#### Answer: C + +Os elementos da matriz podem conter qualquer valor. Números, strings, objetos, outras matrizes, valores nulos, booleanos, indefinidos e outras expressões, como datas, funções e cálculos. + +O elemento será igual ao valor retornado. `1 + 2` retorna` 3`, `1 * 2` retorna` 2` e `1 / 2` retorna` 0,5`. + +

+
+ +--- \ No newline at end of file diff --git a/ro-RO/README.ro.md b/ro-RO/README.ro.md new file mode 100644 index 00000000..93fc1f4e --- /dev/null +++ b/ro-RO/README.ro.md @@ -0,0 +1,5148 @@ +
+ +

Întrebări JavaScript

+ +--- + +Postez întrebări JavaScript cu opțiuni multiple pe [Instagram](https://www.instagram.com/theavocoder) **stories**, pe care le voi posta și aici! Ultima actualizare: 12 Iunie + +De la nivel de bază la avansat: testează cât de bine cunoști JavaScript, reîmprospătează-ți puțin cunoștințele sau pregătește-te pentru interviul tău de codare! :muscle: :rocket: Actualizez acest depozit în mod regulat cu întrebări noi. Am adăugat răspunsurile în **secțiunile restrânse** de sub întrebări, pur și simplu dă clic pe ele pentru a le extinde. Este doar pentru distracție, mult noroc! :heart: + +Nu ezita să mă contactezi! 😊
+Instagram || Twitter || LinkedIn || Blog + +
+ +| Simte-te liber să le folosești într-un proiect! 😃 Aș aprecia _cu adevărat_ o referință la acest depozit, eu creez întrebările și explicațiile (da, sunt tristă lol) și comunitatea mă ajută foarte mult să îl mențin și să îl îmbunătățesc! 💪🏼 Mulțumesc și distracție plăcută! | +|---| + +--- + +
Vezi 20 de traduceri disponibile 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](./ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](./ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](./bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](./de-DE/README.md) +- [🇪🇸 Español](./es-ES/README-ES.md) +- [🇫🇷 Français](./fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](./id-ID/README.md) +- [🇮🇹 Italiano](./it-IT/README.md) +- [🇯🇵 日本語](./ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](./ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](./nl-NL/README.md) +- [🇵🇱 Polski](./pl-PL/README.md) +- [🇧🇷 Português Brasil](./pt-BR/README_pt_BR.md) +- [🇷🇺 Русский](./ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](./th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](./tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](./uk-UA/README.md) +- [🇻🇳 Tiếng Việt](./vi-VI/README-vi.md) +- [🇨🇳 简体中文](./zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](./zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Care este rezultatul? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` și `undefined` +- B: `Lydia` și `ReferenceError` +- C: `ReferenceError` și `21` +- D: `undefined` și `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +În interiorul funcției, mai întâi declarăm variabila `name` cu cuvântul cheie `var`. Acest lucru înseamnă că variabila este hoisted (spațiul de memorie este configurat în faza de creare) cu valoarea implicită `undefined`, până când ajungem efectiv la linia în care definim variabila. Nu am definit încă variabila pe linia în care încercăm să înregistrăm variabila `name`, așa că aceasta păstrează încă valoarea `undefined`. + +Variabilele create cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Acestea nu sunt accesibile înainte de linia în care le declarăm (initializăm). Aceasta se numește zona moartă temporală (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o excepție de tip `ReferenceError`. + +

+
+ +--- + +###### 2. Care este rezultatul? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` și `0 1 2` +- B: `0 1 2` și `3 3 3` +- C: `3 3 3` și `0 1 2` + +
Răspuns +

+ +#### Răspuns: C + +Datorită cozii de evenimente din JavaScript, funcția de callback `setTimeout` este apelată _după_ ce bucla a fost executată. Deoarece variabila `i` din prima buclă a fost declarată folosind cuvântul cheie `var`, această valoare a fost globală. În timpul buclei, am incrementat valoarea lui `i` cu `1` de fiecare dată, folosind operatorul unary `++`. Până când funcția de callback `setTimeout` a fost invocată, `i` era egal cu `3` în primul exemplu. + +În cea de-a doua buclă, variabila `i` a fost declarată folosind cuvântul cheie `let`: variabilele declarate cu cuvântul cheie `let` (și `const`) sunt cu scop la nivel de bloc (un bloc este orice între `{ }`). În fiecare iterație, `i` va avea o valoare nouă, iar fiecare valoare este în cadrul buclei. + +

+
+ +--- + +###### 3. Care este rezultatul? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` și `62.83185307179586` +- B: `20` și `NaN` +- C: `20` și `63` +- D: `NaN` și `63` + +
Răspuns +

+ +#### Răspuns: B + +Rețineți că valoarea lui `diameter` este o funcție obișnuită, în timp ce valoarea lui `perimeter` este o funcție arrow. + +Cu funcțiile arrow, cuvântul cheie `this` se referă la contextul său curent de încadrare, spre deosebire de funcțiile obișnuite! Acest lucru înseamnă că atunci când apelăm `perimeter`, acesta nu se referă la obiectul formei, ci la încadrarea sa curentă (de exemplu, fereastra). + +Nu există nicio valoare `radius` pe acel obiect, ceea ce returnează `NaN`. + +

+
+ +--- + +###### 4. Care este rezultatul? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` și `false` +- B: `false` și `NaN` +- C: `false` și `false` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul unary plus încearcă să convertească un operand într-un număr. `true` este `1`, și `false` este `0`. + +Șirul de caractere `'Lydia'` este o valoare adevărată. Ceea ce întrebăm de fapt, este "este această valoare adevărată falsă?". Acest lucru returnează `false`. + +

+
+ +--- + +###### 5. Care este rezultatul? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` nu este valid +- B: `mouse[bird.size]` nu este valid +- C: `mouse[bird["size"]]` nu este valid +- D: Toate sunt valide + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate cheile obiectelor sunt șiruri de caractere (cu excepția simbolurilor). Chiar dacă nu le _tipizăm_ ca șiruri de caractere, ele sunt întotdeauna convertite în șiruri de caractere în fundal. + +avaScript interpretează (sau dezambalează) instrucțiunile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză pătrată de deschidere `[` și continuă până când găsește paranteza pătrată de închidere `]`. Doar atunci va evalua instrucțiunea. + +`mouse[bird.size]`: Întâi evaluează `bird.size`, care este `"small"`. `mouse["small"]` returnează `true` + +Cu toate acestea, cu notația cu punct, acest lucru nu se întâmplă. `mouse` nu are o cheie numită `bird`, ceea ce înseamnă că `mouse.bird` este `undefined`. Apoi, cerem `size` folosind notația cu punct: `mouse.bird.size`. Deoarece `mouse.bird` este `undefined`, de fapt cerem `undefined.size`. Acest lucru nu este valid și va arunca o eroare similară cu `Cannot read property "size" of undefined` (Nu se poate citi proprietatea "size" a unei valori nedefinite). + +

+
+ +--- + +###### 6. Care este rezultatul? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, toate obiectele interacționează prin _referință_ atunci când sunt setate ca egale între ele. + +Mai întâi, variabila `c` deține o valoare care face referire la un obiect. Ulterior, atribuim variabilei `d` aceeași referință pe care o are `c` la obiect. + + + +Când modifici un obiect, le modifici pe toate. + +

+
+ +--- + +###### 7. Care este rezultatul? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +`new Number()` este un constructor de funcții încorporat. Deși arată ca un număr, nu este într-adevăr un număr: are o mulțime de funcționalități suplimentare și este un obiect. + +Atunci când folosim operatorul `==` (operatorul de egalitate), acesta verifică doar dacă au aceeași _valuare_. Ambele au valoarea `3`, șa că returnează `true`. + +Cu toate acestea, atunci când folosim operatorul `===` (operatorul de egalitate strictă), atât valoarea, cât _și_ tipul trebuie să fie la fel. Nu sunt: `new Number()` nu este un număr, este un **object**. Ambele returnează `false.` + +

+
+ +--- + +###### 8. Care este rezultatul? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: D + +Funcția `colorChange` este statică. Metodele statice sunt concepute să existe doar pe constructorul în care sunt create și nu pot fi transmise către niciun copil sau apelate pe instanțele clasei. Deoarece `freddie` este o instanță a clasei Chameleon, funcția nu poate fi apelată pe aceasta. Se aruncă o eroare de tip `TypeError`. + +

+
+ +--- + +###### 9. Care este rezultatul? + +```javascript +let greeting; +greetign = {}; // Typo! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Se afișează obiectul, deoarece tocmai am creat un obiect gol pe obiectul global! Atunci când am greșit și am scris `greeting` în loc de `greetign`, interpretorul JavaScript a văzut efectiv acest lucru ca: + +1. `global.greetign = {}` în Node.js +2. `window.greetign = {}`, `frames.greetign = {}` și `self.greetign` în browser-e. +3. `self.greetign` în web workers. +4. `globalThis.greetign` în toate mediile. + +Pentru a evita acest lucru, putem folosi `"use strict"`. Acest lucru se asigură că ai declarat o variabilă înainte de a-i atribui o valoare. + +

+
+ +--- + +###### 10. Ce se întâmplă când facem asta? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Nimic, este absolut în regulă! +- B: `SyntaxError`. Nu poți adăuga proprietăți la o funcție în acest fel. +- C: `"Woof"` este înregistrat. +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Acest lucru este posibil în JavaScript, deoarece funcțiile sunt obiecte! (Totul, în afară de tipurile primitive, sunt obiecte) + +O funcție este un tip special de obiect. Codul pe care îl scrii tu însuți nu este funcția efectivă. Funcția este un obiect cu proprietăți. Această proprietate este invocabilă. + +

+
+ +--- + +###### 11. Care este rezultatul? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: A + +În JavaScript, funcțiile sunt obiecte și, prin urmare, metoda `getFullName` este adăugată obiectului constructor al funcției în sine. Din acest motiv, putem apela `Person.getFullName()`, dar `member.getFullName` aruncă o eroare de tip `TypeError`. + +Dacă doriți ca o metodă să fie disponibilă pentru toate instanțele obiectului, trebuie să o adăugați la proprietatea prototype: + +```js +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Care este rezultatul? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` și `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` și `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` și `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` și `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Pentru `sarah`, nu am folosit cuvântul cheie `new`. Când folosim `new`, `this` se referă la noul obiect gol pe care îl creăm. Cu toate acestea, dacă nu adăugăm `new`, `this` se referă la **obiectul global**! + +Am spus că `this.firstName` este egal cu `"Sarah"` și `this.lastName` este egal cu `"Smith"`. Ceea ce am făcut de fapt este să definim `global.firstName = 'Sarah'` și `global.lastName = 'Smith'`. `sarah` în sine rămâne `undefined`, deoarece nu returnăm o valoare din funcția `Person`. + +

+
+ +--- + +###### 13. Care sunt cele trei faze ale propagării evenimentelor? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Răspuns +

+ +#### Răspuns: D + +În timpul fazei de **capturing**, evenimentul trece prin elementele părinte până la elementul țintă. Apoi ajunge la elementul **target**, și începe **bubbling**. + + + +

+
+ +--- + +###### 14. Toate obiectele au prototipuri. + +- A: true +- B: false + +
Răspuns +

+ +#### Răspuns: B + +Toate obiectele au prototipuri, cu excepția **obiectului de bază**. Obiectul de bază este obiectul creat de utilizator sau un obiect creat folosind cuvântul cheie `new`. Obiectul de bază are acces la unele metode și proprietăți, cum ar fi `.toString`. Acesta este motivul pentru care puteți utiliza metode JavaScript încorporate! Toate aceste metode sunt disponibile în prototip. Deși JavaScript nu le poate găsi direct în obiectul dvs., merge în jos pe lanțul prototip și le găsește acolo, ceea ce le face accesibile pentru dvs. + +

+
+ +--- + +###### 15. Care este rezultatul? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Răspuns +

+ +#### Răspuns: C + +JavaScript este un limbaj **dinamic tipizat**: nu specificăm tipurile variabilelor. Valorile pot fi convertite automat în alt tip fără să știți, ceea ce se numește _coerție de tip implicită_. **Coerția** este conversia dintr-un tip în altul. + +În acest exemplu, JavaScript convertește numărul `1` într-un șir de caractere, pentru ca funcția să aibă sens și să returneze o valoare. În timpul adunării unui tip numeric (`1`) și unui tip șir de caractere (`'2'`), numărul este tratat ca un șir de caractere. Putem concatena șiruri de caractere, așa cum facem cu `"Hello" + "World"`, deci ceea ce se întâmplă aici este `"1" + "2"` care returnează `"12"`. + +

+
+ +--- + +###### 16. Care este rezultatul? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Răspuns +

+ +#### Răspuns: C + +Operatorul unary **postfix** `++`: + +1. Returnează valoarea (aceasta returnează `0`) +2. Incrementează valoarea (numărul este acum `1`) + +Operatorul unary **prefix** `++`: + +1. Incrementează valoarea (numărul este acum `2`) +2. Returnează valoarea (aceasta returnează `2`) + +Aceasta returnează `0 2 2`. + +

+
+ +--- + +###### 17. Care este rezultatul? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Răspuns +

+ +#### Răspuns: B + +Dacă utilizați șiruri template etichetate, valoarea primului argument este întotdeauna un șir de valori. Argumentele rămase primesc valorile expresiilor transmise! + +

+
+ +--- + +###### 18. Care este rezultatul? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Răspuns +

+ +#### Răspuns: C + +Când se testează egalitatea, primitivele sunt comparate în funcție de valoarea lor, în timp ce obiectele sunt comparate în funcție de _referința_ lor. JavaScript verifică dacă obiectele au o referință către aceeași locație în memorie. + +Cele două obiecte pe care le comparăm nu au aceeași referință: obiectul pe care l-am trecut ca parametru se referă la o altă locație în memorie decât obiectul pe care l-am folosit pentru a verifica egalitatea. + +Acesta este motivul pentru care ambele `{ age: 18 } === { age: 18 }` și `{ age: 18 } == { age: 18 }` returnează `false`. + +

+
+ +--- + +###### 19. Care este rezultatul? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Răspuns +

+ +#### Răspuns: C + +Parametrul rest (`...args`) ne permite să "colectăm" toate argumentele rămase într-un array. Un array este un obiect, așa că `typeof args` returnează `"object"` + +

+
+ +--- + +###### 20. Care este rezultatul? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: C + +Cu `"use strict"`, puteți asigura că nu declarați accidental variabile globale. Niciodată nu am declarat variabila `age`, și deoarece folosim `"use strict"`, va arunca o eroare de referință. Dacă nu am fi folosit `"use strict"`, ar fi funcționat, deoarece proprietatea `age` ar fi fost adăugată la obiectul global. + +

+
+ +--- + +###### 21. Care este valoarea lui `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Răspuns +

+ +#### Răspuns: A + +`eval` evaluează codul care este trecut ca un șir de caractere. Dacă este o expresie, așa cum este în acest caz, evaluează expresia. Expresia este `10 * 10 + 5`. Aceasta returnează numărul `105`. + +

+
+ +--- + +###### 22. Cât timp este accesibil cool_secret? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Pentru totdeauna, datele nu se pierd. +- B: Când utilizatorul închide fila. +- C: Când utilizatorul închide întregul browser, nu doar fila. +- D: Când utilizatorul oprește computerul. + +
Răspuns +

+ +#### Răspuns: B + +Datele stocate în `sessionStorage` sunt eliminate după închiderea _filei_. + +Dacă ați fi folosit `localStorage`, datele ar fi rămas acolo pentru totdeauna, cu excepția cazului în care, de exemplu, este invocată comanda `localStorage.clear()`. + +

+
+ +--- + +###### 23. Care este rezultatul? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu cuvântul cheie `var`, puteți declara mai multe variabile cu același nume. Variabila va reține apoi cea mai recentă valoare. + +Nu puteți face acest lucru cu `let` sau `const` deoarece acestea sunt cu scop de bloc. + +

+
+ +--- + +###### 24. Care este rezultatul? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +Toate cheile obiectelor (cu excepția simbolurilor) sunt șiruri de caractere în culise, chiar dacă nu le tastați ca șiruri de caractere. De aceea `obj.hasOwnProperty('1')` returnează de asemenea `true`. + +Acest lucru nu funcționează în același fel pentru un set. Nu există `'1'` în setul nostru: `set.has('1')` returnează `false`. Acesta are tipul numeric `1`, `set.has(1)` returnează `true`. + +

+
+ +--- + +###### 25. Care este rezultatul? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: C + +Dacă aveți două chei cu același nume, cheia va fi înlocuită. Va rămâne totuși în prima sa poziție, dar cu ultima valoare specificată. + +

+
+ +--- + +###### 26. Contextul global de execuție JavaScript creează două lucruri pentru dvs.: obiectul global și cuvântul cheie "this". + +- A: true +- B: false +- C: it depends + +
Răspuns +

+ +#### Răspuns: A + +Contextul de execuție de bază este contextul global de execuție: este ceea ce este accesibil peste tot în codul dvs. + +

+
+ +--- + +###### 27. Care este rezultatul? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Răspuns +

+ +#### Răspuns: C + +Instrucțiunea `continue` sare peste o iterație dacă o anumită condiție returnează `true`. + +

+
+ +--- + +###### 28. Care este rezultatul? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()); +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +`String` este un constructor încorporat, la care putem adăuga proprietăți. Am adăugat doar o metodă la prototipul său. Șirurile primitive sunt convertite automat într-un obiect șir, generat de funcția prototip a șirului. Prin urmare, toate șirurile (obiecte de șir) au acces la acea metodă! + +

+
+ +--- + +###### 29. Care este rezultatul? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cheile obiectului sunt convertite automat în șiruri de caractere. Încercăm să setăm un obiect ca cheie pentru obiectul `a`, cu valoarea `123`. + +Cu toate acestea, când transformăm în șir un obiect, acesta devine `"[object Object]"`. Deci ceea ce spunem aici este că `a["[object Object]"] = 123`. Apoi, putem încerca să facem același lucru din nou. `c` este un alt obiect pe care îl transformăm implicit în șir. Așadar, `a["[object Object]"] = 456`. + +Apoi, afișăm înregistrarea `a[b]`, care de fapt este `a["[object Object]"]`. Am setat doar asta la `456`, deci returnează `456`. + +

+
+ +--- + +###### 30. Care este rezultatul? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Răspuns +

+ +#### Răspuns: B + +Avem o funcție `setTimeout` și am invocat-o mai întâi. Cu toate acestea, a fost înregistrată în ultimul rând. + +Acest lucru se datorează faptului că în browsere, nu avem doar motorul de execuție, avem și ceva numit `WebAPI`.`WebAPI` ne oferă funcția `setTimeout` de exemplu, și DOM-ul. + +După ce _callback_-ul este trimis către WebAPI, funcția `setTimeout` în sine (dar nu și callback-ul!) este scos din stivă. + + + +Acum, `foo` este invocată, iar`"First"` este înregistrat. + + + +`foo` este scoasă din stivă, iar `baz` este invocată. Se înregistrează `"Third"`. + + + +WebAPI-ul nu poate adăuga pur și simplu lucruri în stivă atunci când este gata. În schimb, împinge funcția de callback într-o structură numită _coadă_. + + + +Aici începe să lucreze un event loop. Un **event loop** se uită la stivă și la coada de sarcini. Dacă stiva este goală, ia primul lucru din coadă și-l adaugă în stivă. + + + +`bar` este invocată, `"Second"` este înregistrat și este scos din stivă. + +

+
+ +--- + +###### 31. Ce reprezintă "event.target" atunci când se face clic pe buton? + +```html +
+
+ +
+
+``` + +- A: În afara `div` +- B: În interior `div` +- C: `button` +- D: Un șir de toate elementele înglobate. + +
Răspuns +

+ +#### Răspuns: C + +Cel mai profund element înglobat care a cauzat evenimentul este ținta evenimentului. Puteți opri propagarea acestuia prin `event.stopPropagation` + +

+
+ +--- + +###### 32. Când faceți clic pe paragraf, care este ieșirea înregistrată? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Răspuns +

+ +#### Răspuns: A + +Dacă facem clic pe `p`, vom vedea două înregistrări: `p` și `div`. În timpul propagării evenimentului, există 3 faze: capturare, țintă și propagare. În mod implicit, gestionarii de evenimente sunt executați în faza de propagare (cu excepția cazului în care setați `useCapture` la `true`). Aceștia se execută de la cel mai profund element înglobat către exterior. + +

+
+ +--- + +###### 33. Care este rezultatul? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Răspuns +

+ +#### Răspuns: D + +Cu ambele metode, putem transmite obiectul la care dorim să se refere cuvântul cheie `this`. Cu toate acestea, `.call` este de asemenea _executat imediat_! + +`.bind.` returnează o _copie_ a funcției, dar cu un context legat! Nu este executat imediat. + +

+
+ +--- + +###### 34. Care este rezultatul? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Răspuns +

+ +#### Răspuns: B + +Funcția `sayHi` returnează valoarea returnată de expresia funcției invocate imediat (IIFE). This function returned `0`, care este de tip `"number"`. + +Informație utilă: `typeof` poate returna următoarele valori: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` și `object`. Notați că `typeof null` returnează `"object"`. + +

+
+ +--- + +###### 35. Care dintre aceste valori sunt considerate falsy? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Toate dintre ele sunt considerate falsy + +
Răspuns +

+ +#### Răspuns: A + +Există 8 valori considerate falsy: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (șir de caractere gol) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Constructorii de funcții, cum ar fi `new Number` și `new Boolean` sunt considerați truthy. + +

+
+ +--- + +###### 36. Care este rezultatul? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Răspuns +

+ +#### Răspuns: B + +`typeof 1` returnează `"number"`. +`typeof "number"` returnează `"string"` + +

+
+ +--- + +###### 37. Care este rezultatul? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: C + +Când setați o valoare pentru un element într-un array care depășește lungimea array-ului, JavaScript creează ceea ce se numește "slot-uri goale" (empty slots). Acestea au de fapt valoarea `undefined`, dar veți vedea ceva de genul: + +`[1, 2, 3, empty x 7, 11]` + +în funcție de locul în care îl rulați (este diferit pentru fiecare browser, Node.js, etc.) + +

+
+ +--- + +###### 38. Care este rezultatul? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Blocul `catch` primește argumentul `x`. Acesta nu este același `x` ca variabila când transmitem argumente. Această variabilă `x` este având domeniu de bloc (block-scoped). + +Mai târziu, setăm această variabilă cu domeniu de bloc la valoarea `1`, și stabilim valoarea variabilei `y`. Acum, înregistrăm în consolă variabila cu domeniu de bloc `x`, care este egală cu `1`. + +În afara blocului `catch`, `x` rămâne `undefined`, și `y` este `2`. Atunci când dorim să afișăm în consolă `console.log(x)` în afara blocului `catch`, acesta returnează `undefined`, și `y` returnează `2`. + +

+
+ +--- + +###### 39. Totul în JavaScript este fie un... + +- A: primitiv sau obiect +- B: funcție sau obiect +- C: întrebare trucată! doar obiecte +- D: număr sau obiect + +
Răspuns +

+ +#### Răspuns: A + +JavaScript are doar tipuri primitive și obiecte. + +Tipurile primitive sunt `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, și `symbol`. + +Ceea ce diferențiază un tip primitiv de un obiect este faptul că tipurile primitive nu au proprietăți sau metode. Cu toate acestea, veți observa că `'foo'.toUpperCase()` se evaluează la `'FOO'` și nu duce la o eroare `TypeError`. Acest lucru se întâmplă pentru că atunci când încercați să accesați o proprietate sau o metodă pe un tip primitiv, cum ar fi un șir de caractere (string), JavaScript va înconjura implicit tipul primitiv folosind una dintre clasele de înveliș, adică `String`, și apoi va renunța imediat la înveliș după ce expresia se evaluează. Toate tipurile primitive, cu excepția `null` și `undefined` prezintă acest comportament. + +

+
+ +--- + +###### 40. Care este rezultatul? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Răspuns +

+ +#### Răspuns: C + +`[1, 2]` este valoarea noastră inițială. Aceasta este valoarea cu care începem și valoarea primului `acc`. În prima rundă, `acc` este `[1,2]`, și `cur` este `[0, 1]`. Le concatenăm, ceea ce duce la rezultatul `[1, 2, 0, 1]`. + +Atunci, `[1, 2, 0, 1]` este `acc` și `[2, 3]` este `cur`. Le concatenăm și obținem `[1, 2, 0, 1, 2, 3]` + +

+
+ +--- + +###### 41. Care este rezultatul? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Răspuns +

+ +#### Răspuns: B + +`null` este falsy. `!null` returnează `true`. `!true` returnează `false`. + +`""` este falsy. `!""` returnează `true`. `!true` returnează `false`. + +`1` este truthy. `!1` returnează `false`. `!false` returnează `true`. + +

+
+ +--- + +###### 42. Ce returnează metoda `setInterval` în browser? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: un id unic +- B: cantitatea de milisecunde specificată +- C: funcția furnizată +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Aceasta returnează un identificator unic. Acest id poate fi utilizat pentru a opri intervalul respectiv cu ajutorul funcției `clearInterval()`. + +

+
+ +--- + +###### 43. Ce returnează acest lucru? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Răspuns +

+ +#### Răspuns: A + +Un șir de caractere este un obiect iterabil. Operatorul de răspândire (spread operator) mapează fiecare caracter dintr-un obiect iterabil la un element separat. + +

+
+ +--- + +###### 44. Care este rezultatul? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Răspuns +

+ +#### Răspuns: C + +Funcțiile regulate nu pot fi oprite în mijlocul execuției după invocare. Cu toate acestea, o funcție generator poate fi "oprită" în mijloc și ulterior poate continua de la locul unde s-a oprit. De fiecare dată când o funcție generator întâlnește un cuvânt cheie `yield`, funcția furnizează valoarea specificată după el. Notați că funcția generator în acest caz nu _returnează_ the valoarea, ci _furnizează_ valoarea. + +Mai întâi, inițializăm funcția generator cu `i` egal cu `10`. Invocăm funcția generator folosind metoda `next()`. Prima dată când invocăm funcția generator, `i` este egal cu `10`. Aceasta întâlnește primul cuvânt cheie `yield`: furnizează valoarea lui `i`. Generatorul este acum "pauzat", și se înregistrează valoarea `10`. + +Apoi, invocăm din nou funcția cu metoda `next()`. Ea începe să continue de unde s-a oprit anterior, încă cu `i` egal cu `10`. Acum, întâlnește următorul cuvânt cheie `yield`, și furnizează `i * 2`. `i` este egal cu `10`, așa că returnează `10 * 2`, adică `20`. Acest lucru duce la rezultatul `10, 20`. + +

+
+ +--- + +###### 45. Ce returnează asta? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Răspuns +

+ +#### Răspuns: B + +Atunci când transmitem mai multe promisiuni metodei `Promise.race`, ea rezolvă/rejectează _prima_ promisiune care se rezolvă/rejectează. Pentru metoda `setTimeout`, transmitem un cronometru: 500ms pentru prima promisiune (`firstPromise`), și 100ms pentru a doua promisiune (`secondPromise`). Acest lucru înseamnă că `secondPromise` se rezolvă primul cu valoarea `'two'`. `res` conține acum valoarea `'two'`, care se înregistrează în consolă. + +

+
+ +--- + +###### 46. Care este resultatul? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Răspuns +

+ +#### Răspuns: D + +În primul rând, declarăm o variabilă `person` cu valoarea unui obiect care are o proprietate `name`. + + + +Apoi, declarăm o variabilă numită `members`. Setăm primul element al acestui array egal cu valoarea variabilei `person`. Obiectele interacționează prin _referință_ atunci când le setăm egale între ele. Atunci când atribuiți o referință de la o variabilă la alta, faceți o _copie_ a acelei referințe. (notați că acestea nu au _aceași_ referință!) + + + +Apoi, setăm variabila `person` egală cu `null`. + + + +Noi modificăm doar valoarea variabilei `person` nu și primul element din array, deoarece acel element are o referință diferită (copiată) la obiect. Primul element din `members` încă păstrează referința sa la obiectul original. Când înregistrăm în consolă array-ul `members` primul element păstrează valoarea obiectului, care este afișată în consolă. + +

+
+ +--- + +###### 47. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Răspuns +

+ +#### Răspuns: B + +Cu un ciclu `for-in` putem itera prin cheile obiectului, în acest caz `name` și `age`. În interior, cheile obiectului sunt șiruri de caractere (dacă nu sunt de tip Symbol). În fiecare iterație, setăm valoarea lui `item` egală cu cheia curentă pe care o parcurge. Mai întâi, `item` este egal cu `name`, și este înregistrat în consolă. Apoi, `item` este egal cu `age`, care este, de asemenea, înregistrat în consolă. + +

+
+ +--- + +###### 48. Care este rezultatul? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Răspuns +

+ +#### Răspuns: B + +Asociativitatea operatorilor este ordinea în care compilatorul evaluează expresiile, fie de la stânga la dreapta, fie de la dreapta la stânga. Acest lucru se întâmplă doar dacă toți operatorii au aceeași precedență. În cazul nostru, avem doar un tip de operator: `+`. Pentru adunare, asociativitatea este de la stânga la dreapta. + +`3 + 4` este evaluat mai întâi. Acest lucru duce la numărul `7`. + +`7 + '5'` duce la rezultatul `"75"` datorită coerției. JavaScript convertește numărul `7` într-un șir de caractere, așa cum am discutat în întrebarea 15. Putem concatena două șiruri de caractere folosind operatorul `+`. `"7" + "5"` rezultă în `"75"`. + +

+
+ +--- + +###### 49. Care este valoarea lui`num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Răspuns +

+ +#### Răspuns: C + +Este returnat doar primul număr din șir. Bazat pe _radix_ (al doilea argument pentru a specifica în ce tip de număr dorim să-l parsăm: bază 10, hexazecimal, octal, binar, etc.), `parseInt` verifică dacă caracterele din șir sunt valide. Odată ce întâlnește un caracter care nu este un număr valid în baza specificată, oprește parsarea și ignoră caracterele ulterioare. + +`*` nu este un număr valid. Parsează doar `"7"` în numărul zecimal `7`. Acum, `num` conține valoarea `7`. + +

+
+ +--- + +###### 50. Care este rezultatul? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Răspuns +

+ +#### Răspuns: C + +Când se parcurge array-ul, valoarea lui `num` este egală cu elementul prin care parcurge în acel moment. În acest caz, elementele sunt numere, astfel că condiția din instrucțiunea `typeof num === "number"` returnează `true`. Funcția map creează un nou array și introduce valorile returnate de funcție. + +Cu toate acestea, nu returnăm o valoare. Atunci când nu returnăm o valoare din funcție, funcția returnează `undefined`. Pentru fiecare element din array, blocul funcției este apelat, deci pentru fiecare element returnăm `undefined`. + +

+
+ +--- + +###### 51. Care este rezultatul? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Răspuns +

+ +#### Răspuns: A + +Argumentele sunt transmise prin _valoare_, cu excepția cazului în care valoarea lor este un obiect, caz în care sunt transmise prin _referință_. `birthYear` este transmis prin valoare, deoarece este un șir de caractere (string), nu un obiect. Atunci când transmitem argumente prin valoare, se creează o _copie_ a acelei valori (consultați întrebarea 46). + +Variabila `birthYear` are o referință la valoarea `"1997"`. Argumentul `year` are, de asemenea, o referință la valoarea `"1997"`, dar nu este aceeași valoare la care se referă `birthYear`. Atunci când actualizăm valoarea lui `year` prin setarea lui `year` egal cu `"1998"`, actualizăm doar valoarea lui `year`. `birthYear` rămâne în continuare egal cu `"1997"`. + +Valoarea lui `person` este un obiect. Argumentul `member` are o referință (copiată) către _același_ obiect. Atunci când modificăm o proprietate a obiectului la care se referă `member` valoarea lui `person` va fi de asemenea modificată, deoarece ambele au o referință la același obiect. Proprietatea `name` a lui `person` este acum egală cu valoarea `"Lydia"`. + +

+
+ +--- + +###### 52. Care este rezultatul? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Răspuns +

+ +#### Răspuns: D + +Cu instrucțiunea `throw` putem crea erori personalizate. Cu această instrucțiune, puteți arunca excepții. O excepție poate fi un șir de caractere, un număr, un boolean sau un obiect. În acest caz, excepția noastră este șirul `'Hello world!'`. + +Cu instrucțiunea `catch` putem specifica ce să facem dacă o excepție este aruncată în blocul `try`. O excepție este aruncată: șirul `'Hello world!'`. `e` este acum egal cu acel șir, pe care îl înregistrăm. Acest lucru duce la rezultatul `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Care este rezultatul? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: B + +Atunci când o funcție constructor este apelată cu cuvântul cheie `new`, aceasta creează un obiect și stabilește cuvântul cheie `this` să se refere la acel obiect. În mod implicit, dacă funcția constructor nu returnează explicit nimic, va returna obiectul creat recent. + +În acest caz, funcția constructor `Car` returnează în mod explicit un obiect nou cu proprietatea `make` setată la `"Maserati"`, ceea ce suprascrie comportamentul implicit. Prin urmare, atunci când este apelat `new Car()` obiectul _returnat_ este atribuit lui `myCar`, ceea ce duce la rezultatul `"Maserati"` atunci când se accesează `myCar.make`. + +

+
+ +--- + +###### 54. Care este rezultatul? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Răspuns +

+ +#### Răspuns: A + +`let x = (y = 10);` este de fapt o prescurtare pentru + +```javascript +y = 10; +let x = y; +``` + +Când setăm `y` egal cu `10`, adăugăm de fapt o proprietate `y` la obiectul global (`window` într-un browser, `global` în Node). Într-un browser, `window.y` este acum egal cu `10`. + +Apoi, declarăm o variabilă `x` cu valoarea `y`, care este `10`. Variabilele declarate cu cuvântul cheie `let` au domeniu de bloc _block scoped_, ele sunt definite doar în blocul în care sunt declarate; în cazul de față, în funcția expresie invocată imediat (IIFE). Atunci când folosim operatorul `typeof` operandul `x` nu este definit: încercăm să accesăm `x` în afara blocului în care este declarat. Acest lucru înseamnă că `x` nu este definit. Valorile care nu au primit o valoare sau nu au fost declarate sunt de tip `"undefined"`. `console.log(typeof x)` returnează `"undefined"`. + +Cu toate acestea, am creat o variabilă globală `y` atunci când am setat `y` egal cu `10`. Această valoare este accesibilă oriunde în codul nostru. `y` este definită și deține o valoare de tip `"number"`. `console.log(typeof y)` returnează `"number"`. + +

+
+ +--- + +###### 55. Care este rezultatul? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +Putem șterge proprietăți din obiecte folosind cuvântul cheie `delete` inclusiv de pe prototip. Prin ștergerea unei proprietăți de pe prototip, aceasta nu mai este disponibilă în lanțul prototipului. În acest caz, funcția `bark` nu mai este disponibilă pe prototip după `delete Dog.prototype.bark`, dar încercăm totuși să o accesăm. + +Când încercăm să apelăm ceva care nu este o funcție, este aruncată o excepție `TypeError`. În acest caz, se generează eroarea `TypeError: pet.bark is not a function`, deoarece `pet.bark` este `undefined`. + +

+
+ +--- + +###### 56. Care este rezultatul? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Răspuns +

+ +#### Răspuns: D + +Obiectul `Set` este o colecție de valori unice: o valoare poate apărea doar o singură dată într-un set. + +m transmis iterable-ul `[1, 1, 2, 3, 4]` cu o valoare duplicată `1`. Deoarece nu putem avea două valori identice într-un set, una dintre ele este eliminată. Acest lucru duce la rezultatul `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Care este rezultatul? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Răspuns +

+ +#### Răspuns: C + +Un modul importat este _doar pentru citire_: nu puteți modifica modulul importat. Doar modulul care le exportă poate schimba valorile acestora. + +Când încercăm să incrementăm valoarea lui `myCounter`, apare o eroare: `myCounter` este doar pentru citire și nu poate fi modificat. + +

+
+ +--- + +###### 58. Care este rezultatul? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul `delete` returnează o valoare booleană: `true` în cazul ștergerii reușite, în caz contrar va returna `false`. Cu toate acestea, variabilele declarate cu cuvintele cheie `var`, `const` sau `let` nu pot fi șterse folosind operatorul `delete`. + +Variabila `name` a fost declarată cu cuvântul cheie `const` așa că ștergerea sa nu reușește: se returnează `false`. Atunci când setăm `age` egal cu `21`, de fapt am adăugat o proprietate numită `age` la obiectul global. În acest fel, puteți șterge cu succes proprietăți din obiecte, inclusiv din obiectul global, așa că `delete age` returnează `true`. + +

+
+ +--- + +###### 59. Care este rezultatul? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Răspuns +

+ +#### Răspuns: C + +Putem dezasambla (unpack) valori din array-uri sau proprietăți din obiecte prin destructurare. De exemplu: + +```javascript +[a, b] = [1, 2]; +``` + + + +Valoarea lui `a` este acum `1`, iar valoarea lui `b` este acum `2`. Ceea ce am făcut în întrebare este: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Acest lucru înseamnă că valoarea lui `y` este egală cu prima valoare din array, care este numărul `1`. Când înregistrăm în consolă `y`, se returnează `1`. + +

+
+ +--- + +###### 60. Care este rezultatul? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Răspuns +

+ +#### Răspuns: B + +Este posibil să combinăm obiecte folosind operatorul de răspândire`...`. Acesta vă permite să creați copii ale perechilor cheie/valoare dintr-un obiect și să le adăugați la alt obiect. În acest caz, creăm copii ale obiectului `user` și le adăugăm la obiectul `admin`. Obiectul `admin` conține acum perechile cheie/valoare copiate, ceea ce duce la rezultatul `{ admin: true, name: "Lydia", age: 21 }`. + +

+
+ +--- + +###### 61. Care este rezultatul? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `defineProperty` putem adăuga noi proprietăți la un obiect sau să modificăm cele existente. Atunci când adăugăm o proprietate la un obiect folosind metoda `defineProperty` aceasta nu este, în mod implicit, _nu enumerabilă_. Metoda `Object.keys` returnează toate numele de proprietăți _enumerabile_ dintr-un obiect, în acest caz doar `"name"`. + +Proprietățile adăugate folosind metoda `defineProperty` sunt, în mod implicit, imutabile (nu pot fi schimbate). Puteți anula acest comportament folosind proprietățile `writable`, `configurable` și `enumerable` În acest fel, metoda `defineProperty` vă oferă un control mai mare asupra proprietăților pe care le adăugați la un obiect. + +

+
+ +--- + +###### 62. Care este rezultatul? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Răspuns +

+ +#### Răspuns: A + +Al doilea argument al funcției `JSON.stringify` este _replacer-ul_. Replacer-ul poate fi fie o funcție, fie un array, și vă permite să controlați ce și cum ar trebui să fie serializate (convertite în șir de caractere) valorile. + +Dacă replacer-ul este un _array_, în șirul JSON vor fi incluse doar numele de proprietăți care sunt prezente în array. În acest caz, doar proprietățile cu numele `"level"` și `"health"` sunt incluse, în timp ce `"username"` este exclus. Astfel, `data` devine egal cu `"{"level":19, "health":90}"`. + +Dacă replacer-ul este o _funcție_, această funcție este apelată pentru fiecare proprietate din obiectul pe care îl serializați. Valoarea returnată de această funcție va fi valoarea proprietății atunci când este adăugată în șirul JSON. Dacă valoarea este `undefined`, această proprietate este exclusă din șirul JSON. + +

+
+ +--- + +###### 63. Care este rezultatul? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Răspuns +

+ +#### Răspuns: A + +Operatorul unary `++` _returnează mai întâi_ valoarea operandului și _apoi incrementează_ valoarea operandului. Valoarea lui `num1` este `10`, deoarece funcția `increaseNumber` returnează mai întâi valoarea lui `num`, care este `10`, și numai apoi incrementează valoarea lui `num`. + +`num2` este `10`, deoarece am transmis `num1` către funcția `increasePassedNumber`. `number` ieste egal cu `10`(valoarea lui `num1`). Iarăși, operatorul unary `++` _returnează mai întâi_ valoarea operandului și _apoi incrementeazăs_ valoarea operandului. Valoarea lui `number` este `10`, așa că `num2` este egal cu `10`. + +

+
+ +--- + +###### 64. Care este rezultatul? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Răspuns +

+ +#### Răspuns: C + +În ES6, putem inițializa parametri cu o valoare implicită. Valoarea parametrului va fi valoarea implicită, dacă nu a fost furnizată nicio altă valoare funcției sau dacă valoarea parametrului este `"undefined"`. În acest caz, răspândim proprietățile obiectului `value` într-un obiect nou, astfel încât `x` are valoarea implicită `{ number: 10 }`. + +Argumentul implicit este evaluat la _momentul apelului_! De fiecare dată când apelăm funcția, se creează un obiect _nou_. Invocăm funcția `multiply` primele două ori fără a furniza o valoare: `x` are valoarea implicită `{ number: 10 }`. Apoi înregistrăm în consolă valoarea înmulțită a acelui număr, care este `20`. + +A treia oară când apelăm `multiply`, furnizăm un argument: obiectul numit `value`. Operatorul `*=` este, de fapt, o prescurtare pentru `x.number = x.number * 2`: modificăm valoarea lui`x.number`, și înregistrăm în consolă valoarea înmulțită, care este `20`. + +A patra oară, trecem din nou obiectul `value`. `x.number` a fost modificat anterior la `20`, deci `x.number *= 2` înregistrează `40`. + +

+
+ +--- + +###### 65. Care este rezultatul? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` și `3` `3` și `6` `4` +- B: `1` `2` și `2` `3` și `3` `4` +- C: `1` `undefined` și `2` `undefined` și `3` `undefined` și `4` `undefined` +- D: `1` `2` și `undefined` `3` și `undefined` `4` + +
Răspuns +

+ +#### Răspuns: D + +Primul argument pe care îl primește metoda `reduce` este _acumulator-ul_, `x` în acest caz. Al doilea argument este _valoarea curentă_, `y`. Cu metoda `reduce`, executăm o funcție de apel pe fiecare element din array, ceea ce poate duce în cele din urmă la o singură valoare. + +În acest exemplu, nu returnăm nicio valoare, ci doar înregistrăm valorile accumulatorului și valorii curente. + +Valoarea accumulatorului este egală cu valoarea returnată anterior de funcția de apel. Dacă nu furnizați argumentul opțional `initialValue` metodei `reduce`, accumulatorul este egal cu primul element la prima apelare. + +La prima apelare, accumulatorul (`x`) este `1`, iar valoarea curentă (`y`) este `2`. Nu returnăm din funcția de apel, ci înregistrăm valorile accumulatorului și valoarea curentă: se înregistrează `1` și `2`. + +Dacă nu returnați o valoare dintr-o funcție, aceasta va returna `undefined`. OLa următoarea apelare, accumulatorul este `undefined`, iar valoarea curentă este `3`. Se înregistrează `undefined` și `3`. + +La a patra apelare, din nou nu returnăm din funcția de apel. Accumulatorul este din nou `undefined`, iar valoarea curentă este `4`. Se înregistrează `undefined` și `4`. + +

+
+ +--- + +###### 66. Cu ce constructor putem extinde cu succes clasa `Dog`? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Răspuns +

+ +#### Răspuns: B + +Într-o clasă derivată, nu puteți accesa cuvântul cheie `this` înainte de a apela `super`. Dacă încercați să faceți acest lucru, va arunca o ReferenceError: 1 și 4 ar arunca o eroare de referință. + +Cu cuvântul cheie `super`, apelăm constructorul clasei părinte cu argumentele date. Constructorul părintelui primește argumentul `name`, deci trebuie să transmitem `name` la `super`. + +Clasa `Labrador` primește doi argumente, `name` deoarece extinde clasa `Dog`, și `size` ca o proprietate suplimentară în clasa `Labrador`. Ambele trebuie să fie transmise funcției constructor din clasa `Labrador`, ceea ce se face corect utilizând constructorul 2. + +

+
+ +--- + +###### 67. Care este rezultatul? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Răspuns +

+ +#### Răspuns: B + +Cu cuvântul cheie `import`, toate modulele importate sunt _preparate în prealabil_. Acest lucru înseamnă că modulele importate sunt executate _mai întâi_, codul din fișierul care importă modulul este executat _după accea_. + +Acesta este un diferență între `require()` în CommonJS și `import`! Cu `require()`, puteți încărca dependențele la cerere în timp ce codul este în curs de desfășurare. Dacă am fi folosit `require` în loc de `import`, ar fi fost înregistrate în consolă mesajele `running index.js`, `running sum.js`, `3`. + +

+
+ +--- + +###### 68. Care este rezultatul? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Răspuns +

+ +#### Răspuns: A + +Fiecare Symbol este complet unic. Scopul argumentului furnizat către Symbol este de a oferi Symbolului o descriere. Valoarea Symbolului nu depinde de argumentul furnizat. În timp ce testăm egalitatea, creăm două simboluri complet noi: primul `Symbol('foo')`, și al doilea `Symbol('foo')`. Aceste două valori sunt unice și nu sunt egale între ele, `Symbol('foo') === Symbol('foo')` returnează `false`. + +

+
+ +--- + +###### 69. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Răspuns +

+ +#### Răspuns: C + +Cu metoda `padStart` putem adăuga umplutură la începutul unui șir. Valoarea transmisă acestei metode este lungimea _totală_ a șirului împreună cu umplutura. Șirul `"Lydia Hallie"` are o lungime de `12`. `name.padStart(13)` introduce 1 spațiu la începutul șirului, deoarece 12 + 1 este 13. + +Dacă argumentul transmis metodei `padStart` este mai mic decât lungimea șirului, nu va fi adăugată nicio umplutură. + +

+
+ +--- + +###### 70. Care este rezultatul? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Un șir care conține punctele de cod ale caracterelor +- D: Eroare + +
Răspuns +

+ +#### Răspuns: A + +Cu operatorul `+`, puteți concatena șiruri. În acest caz, concatenăm șirul `"🥑"` cu șirul `"💻"`, rezultând `"🥑💻"`. + +

+
+ +--- + +###### 71. Cum putem înregistra valorile aflate în comentarii după instrucțiunea console.log? + +```javascript +function* startGame() { + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` și `game.next().value` +- B: `game.next.value("Yes")` și `game.next.value()` +- C: `game.next().value` și `game.next("Yes").value` +- D: `game.next.value()` și `game.next.value("Yes")` + +
Răspuns +

+ +#### Răspuns: C + +O funcție generator "pauzează" execuția când întâlnește cuvântul cheie `yield`. Mai întâi, trebuie să permitem funcției să emită șirul "Do you love JavaScript?", ceea ce poate fi făcut apelând `game.next().value`. + +Fiecare linie este executată până când găsește primul cuvânt cheie `yield`. Există un cuvânt cheie `yield` pe prima linie din funcție: execuția se oprește cu primul `yield`. _Acest lucru înseamnă că variabila `answer` nu este definită încă!_ + +Când apelăm `game.next("Yes").value`, cuvântul cheie `yield` anterior este înlocuit cu valoarea parametrilor transmiși funcției `next()`, `"Yes"` în acest caz. Valoarea variabilei `answer` este acum egală cu `"Yes"`. Condiția declarației if returnează `false`, și `JavaScript loves you back ❤️` este înregistrat în consolă. + +

+
+ +--- + +###### 72. Care este rezultatul? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`
     `world` +- C: `Hello\nworld` +- D: `Hello\n`
     `world` + +
Răspuns +

+ +#### Răspuns: C + +`String.raw` returnează un șir în care escape-urile (`\n`, `\v`, `\t` etc.) sunt ignorate! Backslash-urile pot fi o problemă, deoarece puteți ajunge cu ceva similar cu: + +`` const path = `C:\Documents\Projects\table.html` `` + +Acest lucru ar rezulta în: + +`"C:DocumentsProjects able.html"` + +Cu `String.raw`, acesta ar ignora pur și simplu escape-ul și ar afișa: + +`C:\Documents\Projects\table.html` + +În acest caz, șirul este `Hello\nworld`, care este înregistrat în consolă. + +

+
+ +--- + +###### 73. Care este rezultatul? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +O funcție `async` întotdeauna returnează o promisiune. Instrucțiunea `await` încă trebuie să aștepte ca promisiunea să se rezolve: o promisiune în așteptare este returnată atunci când apelăm `getData()` pentru a o atribui variabilei `data`. + +Dacă dorim să avem acces la valoarea rezolvată `"I made it"`, am putea folosi metoda `.then()` pe `data`: + +`data.then(res => console.log(res))` + +Acest lucru ar fi înregistrat `"I made it!"` + +

+
+ +--- + +###### 74. Care este rezultatul? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Metoda`.push()` returnează _lungimea_ noului șir! Înainte, șirul conținea un element (șirul `"banana"`) și avea o lungime de `1`. După adăugarea șirului `"apple"` în șir, șirul conține două elemente și are o lungime de `2`. Aceasta este valoarea returnată de funcția `addToList`. + +Metoda `push` modifică șirul original. Dacă doreați să returnați _șirul_ din funcție în loc de _lungimea șirului_, ar fi trebuit să returnați `list` după ce ați adăugat `item` la el. + +

+
+ +--- + +###### 75. Care este rezultatul? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +`Object.freeze` face imposibilă adăugarea, eliminarea sau modificarea proprietăților unui obiect (cu excepția cazului în care valoarea proprietății este un alt obiect). + +Când creăm variabila `shape` și o setăm egală cu obiectul înghețat `box`, `shape` de asemenea se referă la un obiect înghețat. Puteți verifica dacă un obiect este înghețat folosind `Object.isFrozen`. În acest caz, `Object.isFrozen(shape)` ar returna true, deoarece variabila `shape` are o referință către un obiect înghețat. + +Deoarece `shape` este înghețat și deoarece valoarea lui`x` nu este un obiect, nu putem modifica proprietatea `x`. `x` rămâne egal cu `10`, și `{ x: 10, y: 20 }` este afișat în consolă. + +

+
+ +--- + +###### 76. Care este rezultatul? + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; + +console.log(firstName); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Folosind [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) cu sintaxa de mai jos putem extrage valori din array-uri sau proprietăți din obiecte în variabile distincte: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// ES5 version: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +De asemenea, o proprietate poate fi extras dintr-un obiect și atribuită unei variabile cu un nume diferit decât proprietatea obiectului: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// ES5 version: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Prin urmare, `firstName` nu există ca variabilă, astfel încât încercarea de a accesa valoarea sa va genera o eroare `ReferenceError`. + +**Notă:** Fiți conștienți de proprietățile în `global scope` (spațiul global): + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser e.g. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +În cazul în care JavaScript nu poate găsi o variabilă în _cadrul curent_, acesta urcă pe [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) și o caută. Dacă ajunge la nivelul superior al cadrului, adică la **spațiul global**, și tot nu o găsește, va arunca o excepție `ReferenceError`. + +- În **Browser-e** cum ar fi _Chrome_, `name` este o _proprietate de spațiu global depășită_. În acest exemplu, codul rulează în _spațiul global_ și nu există o variabilă locală definită de utilizator pentru `name`, așa că caută _variabilele/proprietățile_ predefinite în spațiul global, care în cazul browser-elor înseamnă că caută în obiectul `window` de unde extrage valoarea [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) care este egală cu un **șir gol**. + +- În **NodeJS**, nu există o astfel de proprietate pe obiectul `global` așadar încercarea de a accesa o variabilă inexistentă va genera o [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). + +

+
+ +--- + +###### 77. Este aceasta o funcție pură? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Da +- B: Nu + +
Răspuns +

+ +#### Răspuns: A + +O funcție pură este o funcție care _întotdeauna_ returnează același rezultat, dacă aceleași argumente sunt furnizate. + +Funcția `sum` întotdeauna returnează același rezultat. Dacă îi furnizăm `1` și `2`, va returna _întotdeauna_ `3` fără efecte secundare. Dacă îi furnizăm `5` și `10`, va returna _întotdeauna_ `15`, și tot așa. Aceasta este definiția unei funcții pure. + +

+
+ +--- + +###### 78. Care este rezultatul? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Răspuns +

+ +#### Răspuns: C + +Funcția `add` este o funcție _memoizată_. Cu ajutorul memoizării, putem să memorăm rezultatele unei funcții pentru a accelera execuția ulterioară. În acest caz, creăm un obiect `cache` care stochează valorile returnate anterior. + +Dacă apelăm din nou funcția `addFunction` cu același argument, funcția verifică mai întâi dacă a primit deja acea valoare în memoria sa cache. Dacă acest lucru este adevărat, se va returna valoarea din cache, economisind timp de execuție. Dacă nu este în cache, funcția va calcula valoarea și o va memora ulterior. + +Apelăm funcția `addFunction` de trei ori cu aceeași valoare: în prima invocare, valoarea funcției când `num` este egal cu `10` nu este încă în cache. Condiția instrucțiunii `num in cache` returnează `false`, iar blocul `else` este executat: se afișează `Calculated! 20` iar valoarea rezultatului este adăugată în obiectul de cache. Acum, `cache` arată astfel `{ 10: 20 }`. + +A doua oară, obiectul `cache` conține valoarea care este returnată pentru `10`. Condiția instrucțiunii `num in cache` returnează `true`, și se afișează `'From cache! 20'`. + +A treia oară, trecem `5 * 2` funcției, care este evaluat la `10`. Obiectul `cache` conține valoarea care este returnată pentru `10`. Condiția instrucțiunii `num in cache` returnează `true`, și se afișează `'From cache! 20'`. + +

+
+ +--- + +###### 79. Care este rezultatul? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` și `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` și `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` și `0` `1` `2` `3` +- D: `0` `1` `2` `3` și `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Răspuns +

+ +#### Răspuns: A + +Cu o buclă _for-in_, putem itera peste proprietățile **enumerabile**. Într-un șir, proprietățile enumerate sunt "cheile" elementelor din șir, care sunt de fapt indexurile lor. Puteți vedea un șir ca: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Unde cheile sunt proprietățile enumerate. `0` `1` `2` `3` sunt afișate. + +Cu o buclă _for-of_, putem itera peste obiecte **iterabile**. Un șir este un obiect iterabil. Când iterăm peste șir, variabila "item" este egală cu elementul pe care îl parcurge în acel moment, sunt afișate `"☕"` `"💻"` `"🍷"` `"🍫"`. + +

+
+ +--- + +###### 80. Care este rezultatul? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Răspuns +

+ +#### Răspuns: C + +Elementele dintr-un șir pot stoca orice valoare. Numere, șiruri, obiecte, alte șiruri, null, valori booleane, undefined și alte expresii precum date, funcții și calculații. + +Elementul va fi egal cu valoarea returnată. `1 + 2` returnează `3`, `1 * 2` returnează `2`, și `1 / 2` returnează `0.5`. + +

+
+ +--- + +###### 81. Care este rezultatul? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +În mod implicit, argumentele au valoarea `undefined`, cu excepția cazului în care s-a transmis o valoare funcției. În acest caz, nu am transmis o valoare pentru argumentul `name`. `name` este egal cu `undefined` iar acesta este afișat. + +În ES6, putem suprascrie această valoare implicită `undefined` cu parametri impliciti. De exemplu: + +`function sayHi(name = "Lydia") { ... }` + +În acest caz, dacă nu am fi furnizat o valoare sau am fi furnizat `undefined`, `name` ar fi fost întotdeauna egal cu șirul `Lydia`. + +

+
+ +--- + +###### 82. Care este rezultatul? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` și `"😍"` +- B: `"🥑"` și `"😎"` +- C: `"😍"` și `"😎"` +- D: `"😎"` și `"😎"` + +
Răspuns +

+ +#### Răspuns: B + +Valoarea cuvântului cheie `this` depinde de locul în care este utilizat. Într-o **metodă**, cum ar fi metoda `getStatus`, cuvântul cheie `this` se referă la _obiectul la care aparține metoda_. Metoda aparține obiectului `data`, deci `this` se referă la obiectul `data`. Când înregistrăm `this.status`, se înregistrează proprietatea `status` de pe obiectul `data` care este `"🥑"`. + +Cu metoda `call` putem schimba obiectul la care se referă cuvântul cheie `this`. În **funcții**, cuvântul cheie `this` se referă la _obiectul la care aparține funcția_. Am declarat funcția `setTimeout` pe _obiectul global_, deci în interiorul funcției `setTimeout`, cuvântul cheie `this` se referă la _obiectul global_. Pe obiectul global există o variabilă numită status cu valoarea `"😎"`. Când înregistrați `this.status`, se înregistrează `"😎"`. + +

+
+ +--- + +###### 83. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Răspuns +

+ +#### Răspuns: A + +Am setat variabila `city` egală cu valoarea proprietății numită `city` pe obiectul `person`. Nu există o proprietate pe acest obiect numită `city`, astfel că variabila `city` are valoarea `undefined`. + +Rețineți că nu facem referire la obiectul `person` în sine! Pur și simplu am setat variabila `city` egală cu valoarea curentă a proprietății `city` de pe obiectul `person`. + +Apoi, am setat `city` egal cu șirul de caractere `"Amsterdam"`. Acest lucru nu schimbă obiectul `person` nu există o referință la acel obiect. + +Atunci când se afișează obiectul `person` se va afișa obiectul original, nealterat. + +

+
+ +--- + +###### 84. Care este rezultatul? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Variabilele declarate cu cuvintele cheie `const` și `let` au _domeniu de vizibilitate la nivel de bloc_. Un bloc poate fi definit între parantezele acolade (`{ }`). În acest caz, parantezele acolade ale instrucțiunilor if/else. Nu puteți face referire la o variabilă în afara blocului în care a fost declarată, va fi generată o eroare de tip ReferenceError. + +

+
+ +--- + +###### 85. Ce tip de informații ar fi înregistrate? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Rezultatul metodei `fetch`. +- B: Rezultatul celei de-a doua apelări a metodei `fetch`. +- C: Rezultatul funcției de retur (callback) din `.then()`-ul anterior. +- D: Ar fi întotdeauna `undefined`. + +
Răspuns +

+ +#### Răspuns: C + +Valoarea lui `res` în al doilea `.then` este egală cu valoarea returnată de `.then` anterior. Puteți continua să înșirați `.then`-uri în acest fel, unde valoarea este pasată către următorul manipulator. + +

+
+ +--- + +###### 86. Care opțiune este o modalitate de a seta `hasName` egala cu `true`, cu condiția să nu puteți furniza `true` ca argument? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Răspuns +

+ +#### Răspuns: A + +Cu `!!name`, determinăm dacă valoarea lu `name` este adevărată sau falsă. Dacă `name` este adevărat, ceea ce dorim să testăm, `!name` returnează `false`. `!false` (practic, ceea ce este `!!name`) returnează `true`. + +Prin setarea lui `hasName` egal cu `name`, se face ca `hasName` să fie egal cu valoarea pe care ați furnizat-o funcției `getName`, nu cu valoarea booleană `true`. + +`new Boolean(true)` returnează un obiect încapsulator, nu valoarea booleană în sine. + +`name.length` returnează lungimea argumentului furnizat, nu dacă acesta este `true`. + +

+
+ +--- + +###### 87. Care este rezultatul? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Pentru a obține un caracter la un anumit index dintr-un șir de caractere, puteți utiliza notația cu paranteze pătrate. Primul caracter din șir are indexul 0, și așa mai departe. În acest caz, dorim să obținem elementul cu indexul 0, adică caracterul `"I'`, care va fi afișat în jurnal. + +Rețineți că această metodă nu este suportată în IE7 și versiunile anterioare. În acest caz, utilizați `.charAt()`. + +

+
+ +--- + +###### 88. Care este rezultatul? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Puteți seta valoarea implicită a unui parametru la valoarea altui parametru al funcției, atâta timp cât acestea sunt definite _înainte_ de parametrul cu valoarea implicită. Am transmis valoarea `10` funcției `sum`. Dacă funcția `sum` primește doar un argument, înseamnă că valoarea pentru `num2` nu este transmisă, iar valoarea lui `num1` este egală cu valoarea transmisă `10` în acest caz. Valoarea implicită a lui `num2` este valoarea lui `num1`, care este `10`. `num1 + num2` returnează `20`. + +Dacă încercați să setați valoarea implicită a unui parametru egală cu un parametru care este definit _după_ (în dreapta), valoarea parametrului nu a fost încă inițializată, ceea ce va genera o eroare. + +

+
+ +--- + +###### 89. Care este rezultatul? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Obiectul global al `module.js` + +
Răspuns +

+ +#### Răspuns: A + +Cu sintaxa `import * as name`, importăm _toate exporturile_ din fișierul `module.js` în fișierul `index.js` sub forma unui nou obiect numit `data`. În fișierul `module.js` există două exporturi: exportul implicit și un export cu nume. Exportul implicit este o funcție care returnează șirul de caractere `"Hello World"`, iar exportul cu nume este o variabilă numită `name` care are valoarea șirului de caractere `"Lydia"`. + +Obiectul `data` are o proprietate `default` pentru exportul implicit, iar celelalte proprietăți au numele exporturilor cu nume și valorile lor corespunzătoare. + +

+
+ +--- + +###### 90. Care este rezultatul? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Răspuns +

+ +#### Răspuns: C + +Clasele sunt o sintaxă mai simplă pentru constructorii de funcții. Echivalentul clasei `Person` sub forma unui constructor de funcții ar fi: + +```javascript +function Person(name) { + this.name = name; +} +``` + +Apelarea unui constructor de funcții cu `new` duce la crearea unei instanțe a obiectului `Person`, iar cuvântul cheie `typeof` returnează `"object"` pentru o astfel de instanță. `typeof member` returnează `"object"`. + +

+
+ +--- + +###### 91. Care este rezultatul? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `.push` returnează _lungimea nouă_ a array-ului, nu array-ul însuși! Prin setarea `newList` egal cu `[1, 2, 3].push(4)`, am setat `newList` egal cu noua lungime a array-ului: `4`. + +Apoi, încercăm să folosim metoda `.push` pe `newList`. Deoarece `newList` este o valoare numerică `4`, nu putem folosi metoda `.push` se va genera o eroare de tip TypeError. + +

+
+ +--- + +###### 92. Care este rezultatul? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Răspuns +

+ +#### Răspuns: D + +Funcțiile obișnuite, cum ar fi funcția `giveLydiaPizza` au o proprietate `prototype` care este un obiect (obiectul prototip) cu o proprietate `constructor`. Cu toate acestea, funcțiile arrow, cum ar fi funcția `giveLydiaChocolate`, nu au această proprietate `prototype`. `undefined` este returnat atunci când încearca să acceseze proprietatea `prototype` folosind `giveLydiaChocolate.prototype`. + +

+
+ +--- + +###### 93. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` și `age` `21` +- B: `["name", "Lydia"]` și `["age", 21]` +- C: `["name", "age"]` și `undefined` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: A + +`Object.entries(person)` returnează un array de array-uri imbricate, care conțin cheile și obiectele: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Folosind bucla `for-of` putem itera prin fiecare element din array, în acest caz, subarray-urile. Putem dezasambla subarray-urile instantaneu în bucla `for-of`, folosind `const [x, y]`. Astfel, `x` este egal cu primul element din subarray, iar `y` este egal cu al doilea element din subarray. + +Primul subarray este `[ "name", "Lydia" ]`, cu `x` egal cu `"name"`, și `y` egal cu `"Lydia"`, care sunt afișate în jurnal. +Al doilea subarray este `[ "age", 21 ]`, cu `x` egal cu `"age"`, și `y` egal cu `21`, care sunt afișate în jurnal. + +

+
+ +--- + +###### 94. Care este rezultatul? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: D + +`...args` este un parametru rest. Valoarea parametrului rest este un array care conține toate argumentele rămase și **poate fi doar ultimul parametru**! În acest exemplu, parametrul rest era al doilea parametru. Acest lucru nu este posibil și va genera o eroare de sintaxă. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +Exemplul de mai sus funcționează. Acesta returnează array-ul `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Care este rezultatul? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` și `b is bigger`, `3` +- B: `a is bigger`, `undefined` și `b is bigger`, `undefined` +- C: `undefined` și `undefined` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +În JavaScript, nu _trebuie_ să scriem explicit semnul punct și virgulă (`;`) totuși motorul JavaScript le adaugă automat după instrucțiuni. Acest lucru se numește **Inserția Automată a Semnelor de Punct și Virgulă**. O instrucțiune poate fi, de exemplu, variabile sau cuvinte cheie precum `throw`, `return`, `break`, etc. + +Aici, am scris o instrucțiune `return` și o altă valoare `a + b` pe o _linie nouă_. Cu toate acestea, deoarece este o linie nouă, motorul JavaScript nu știe că este de fapt valoarea pe care am dorit să o returnăm. În schimb, a adăugat automat un punct și virgulă după `return`. Puteți vedea acest lucru ca: + +```javascript +return; +a + b; +``` + +Acest lucru înseamnă că `a + b` nu este niciodată atins, deoarece o funcție se oprește din executare după cuvântul cheie `return`. Dacă nu se returnează nicio valoare, așa cum se întâmplă aici, funcția returnează `undefined`. Rețineți că nu există inserție automată a semnelor de punct și virgulă după instrucțiunile `if/else`! + +

+
+ +--- + +###### 96. Care este rezultatul? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +Putem seta clasele egale cu alte clase sau constructori de funcții. În acest caz, am setat `Person` egal cu `AnotherPerson`. Numele în acest constructor este `Sarah`, astfel încât proprietatea `Person` de pe noua instanță `member` este `"Sarah"`. + +

+
+ +--- + +###### 97. Care este rezultatul? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` și `["{Symbol('a')"]` +- B: `{}` și `[]` +- C: `{ a: "b" }` și `["a"]` +- D: `{Symbol('a'): 'b'}` și `[]` + +
Răspuns +

+ +#### Răspuns: D + +Un simbol nu este _enumerabil_. Metoda `Object.keys` returnează toate proprietățile cheie _enumerabil_ ale unui obiect. Simbolul nu va fi vizibil, și va fi returnat un array gol. Atunci când se afișează întregul obiect, vor fi vizibile toate proprietățile, inclusiv cele care nu sunt enumerate. + +Asta este una dintre multele calități ale unui simbol: pe lângă faptul că reprezintă o valoare complet unică (ceea ce previne coliziunile accidentale de nume pe obiecte, de exemplu, atunci când lucrați cu două biblioteci care doresc să adauge proprietăți la același obiect), puteți "ascunde" proprietăți pe obiecte în acest fel (deși nu în întregime. Încă puteți accesa simbolurile folosind metoda `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Care este rezultatul? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` și `SyntaxError` +- B: `[1, [2, 3, 4]]` și `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` și `{ name: "Lydia", age: 21 }` +- D: `Error` și `{ name: "Lydia", age: 21 }` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `getList` primește un array ca argument. Între parantezele funcției `getList` dezasamblăm acest array imediat. Puteți vedea acest lucru ca: + +`[x, ...y] = [1, 2, 3, 4]` + +Cu ajutorul parametrului rest `...y`, punem toți "parametrii rămași" într-un array. Parametrii rămași în acest caz sunt `2`, `3` și `4`. Valoarea lui `y` este un array care conține toți parametrii rămași. Valoarea lui `x` este egal cu `1` în acest caz, deci când afișăm `[x, y]`, va fi afișat `[1, [2, 3, 4]]`. + +Funcția `getUser` primește un obiect ca argument. Cu funcțiile arrow, nu _trebuie_ să scriem acolade dacă dorim să returnăm doar o valoare. Cu toate acestea, dacă doriți să returnați instantaneu un _obiect_ dintr-o funcție arrow, trebuie să-l scrieți între paranteze. Altfel, tot ce este între acolade va fi interpretat ca o instrucțiune bloc. În acest caz, codul dintre acolade nu este un cod JavaScript valid, așa că se va genera o eroare de sintaxă `SyntaxError`. + +Funcția următoare ar fi returnat un obiect: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Care este rezultatul? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Variabila `name` conține o valoare de tip șir de caractere (string), care nu este o funcție și, prin urmare, nu poate fi invocată. + +TypeError-urile sunt generate atunci când o valoare nu este de tipul așteptat. JavaScript e aștepta ca `name` să fie o funcție, deoarece încercăm să o apelăm. Cu toate acestea, era de tip șir de caractere (string), așa că a generat o eroare de tip TypeError: name nu este o funcție! + +SyntaxError-urile sunt generate atunci când ați scris ceva care nu este JavaScript valid, de exemplu, atunci când ați scris cuvântul `return` ca `retrun`. +ReferenceError-urile sunt generate atunci când JavaScript nu poate găsi o referință la o valoare la care încercați să accesați. + +

+
+ +--- + +###### 100. Care este valoarea lui output? + +```javascript +// 🎉✨ Aceasta este a 100-a mea întrebare! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Răspuns +

+ +#### Răspuns: B + +`[]` este o valoare adevărată (truthy). Cu operatorul `&&` valoarea din partea dreaptă va fi returnată dacă valoarea din partea stângă este adevărată. În acest caz, valoarea din partea stângă, `[]` este adevărată, astfel că se va returna `"Im'`. + +`""` este o valoare falsă (falsy). Dacă valoarea din partea stângă este falsă, nu se returnează nimic. `n't` nu va fi returnat. + +

+
+ +--- + +###### 101. Care este valoarea ieșirii? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Răspuns +

+ +#### Răspuns: C + +Cu operatorul `||` utem returna primul operand adevărat (truthy). Dacă toate valorile sunt false, se va returna ultimul operand. + +`(false || {} || null)`: obiectul go `{}` este o valoare adevărată (truthy). Aceasta este prima (și singura) valoare adevărată, care este returnată. `one` este egal cu `{}`. + +`(null || false || "")`: toate operanzii sunt valori false. Acest lucru înseamnă că ultimul operand `""` este returnat. `two` este egal cu `""`. + +`([] || 0 || "")`: array-ul gol `[]` este o valoare adevărată (truthy). Aceasta este prima valoare adevărată, care este returnată. `three` este egal cu `[]`. + +

+
+ +--- + +###### 102. Care este valoarea ieșirii? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` și `I have resolved!`, `second` +- B: `second`, `I have resolved!` și `second`, `I have resolved!` +- C: `I have resolved!`, `second` și `second`, `I have resolved!` +- D: `second`, `I have resolved!` și `I have resolved!`, `second` + +
Răspuns +

+ +#### Răspuns: D + +Cu o promisiune, spunem în principiu _Vreau să execut această funcție, dar o pun deoparte pentru moment în timp ce rulează, deoarece acest lucru poate dura ceva timp. Doar atunci când o anumită valoare este rezolvată (sau respinsă), și atunci când stiva de apeluri este goală, doresc să folosesc această valoare._ + +Putem obține această valoare atât cu `.then` cât și cu cuvântul cheie `await` într-o funcție `async`. Cu toate că putem obține valoarea unei promisiuni cu ambele metode `.then` și `await`, ele funcționează puțin diferit. + +În `firstFunction`, am pus (într-un fel) funcția `myPromise` deoparte în timp ce aceasta se executa, dar am continuat să executăm restul codului, care este `console.log('second')` în acest caz. Apoi, funcția a fost rezolvată cu șirul `I have resolved`, care a fost apoi înregistrat în jurnal după ce s-a constatat că stiva de apeluri era goală. + +Cu cuvântul cheie `await` în `secondFunction`, efectiv pauzăm execuția unei funcții asincrone până când valoarea a fost rezolvată înainte de a trece la următoarea linie. + +Acest lucru înseamnă că a așteptat ca `myPromise` să fie rezolvat cu valoarea `I have resolved`, și doar după ce s-a întâmplat acest lucru, s-a trecut la următoarea linie: a fost înregistrat `second`. + +

+
+ +--- + +###### 103. Care este valoarea ieșirii? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Răspuns +

+ +#### Răspuns: C + +Operatorul `+` nu este folosit doar pentru adunarea valorilor numerice, ci îl putem utiliza și pentru concatenarea șirurilor de caractere. Ori de câte ori motorul JavaScript observă că una sau mai multe valori nu sunt de tip număr, va converti numărul într-un șir de caractere. + +Primul operand este `1`, care este o valoare numerică. `1 + 2` returnează numărul 3. + +Cu toate acestea, al doilea operand este un șir de caractere `"Lydia"`. `"Lydia"` este un șir de caractere și `2` este un număr: `2` este convertit într-un șir de caractere. `"Lydia"` și `"2"` sunt concatenate, rezultând șirul de caractere `"Lydia2"`. + +`{ name: "Lydia" }` este un obiect. Niciun număr, niciun obiect nu este un șir de caractere, astfel că sunt convertite în șiruri. Ori de câte ori convertim un obiect regulat în șir de caractere, devine `"[object Object]"`. `"[object Object]"` concatenat cu `"2"` devine `"[object Object]2"`. + +

+
+ +--- + +###### 104. Care este rezultatul? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Răspuns +

+ +#### Răspuns: C + +Putem pasa orice tip de valoare dorim către `Promise.resolve`, fie o promisiune, fie o valoare non-promisiune. Metoda în sine returnează o promisiune cu valoarea rezolvată (``). Dacă pasați o funcție regulată, va fi o promisiune rezolvată cu o valoare regulată. Dacă pasați o promisiune, va fi o promisiune rezolvată cu valoarea rezolvată a promisiunii respective pasate. + +În acest caz, am pasat doar valoarea numerică `5`. Aceasta returnează o promisiune rezolvată cu valoarea `5`. + +

+
+ +--- + +###### 105. Care este rezultatul? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: B + +Obiectele sunt pasate prin referință. Atunci când verificăm obiecte pentru egalitate strictă (`===`), comparăm referințele lor. + +Am setat valoarea implicită pentru `person2` egală cu obiectul `person` și am pasat obiectul `person` ca valoare pentru `person1`. + +Acest lucru înseamnă că ambele valori au o referință către aceeași locație în memorie, astfel că sunt egale. + +Blocul de cod din instrucțiunea `else` se execută, și este înregistrat mesajul`They are the same!`. + +

+
+ +--- + +###### 106. Care este rezultatul? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: D + +În JavaScript, avem două moduri de a accesa proprietăți pe un obiect: notare cu paranteze pătrate sau notare cu punct. În acest exemplu, folosim notarea cu punct (`colorConfig.colors`) în loc de notarea cu paranteze pătrate (`colorConfig["colors"]`). + +Cu notarea cu punct, JavaScript încearcă să găsească proprietatea pe obiect cu exact același nume. În acest exemplu, JavaScript încearcă să găsească o proprietate numită `colors` pe obiectul `colorConfig`. Nu există o proprietate numită `colors`, așa că acest lucru returnează `undefined`. Apoi, încercăm să accesăm valoarea primului element folosind `[1]`. Nu putem face acest lucru pe o valoare care este `undefined`, astfel că se generează o eroare de tip `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript interpretează (sau deschide) declarațiile. Atunci când folosim notația cu paranteze pătrate, vede prima paranteză deschisă `[` și continuă până găsește paranteza de închidere `]`. Abia atunci va evalua declarația. Dacă am fi folosit `colorConfig[colors[1]]`, ar fi returnat valoarea proprietății `red` pe obiectul `colorConfig`. + +

+
+ +--- + +###### 107. Care este rezultatul? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Răspuns +

+ +#### Răspuns: A + +În culise, emoji-urile sunt reprezentate ca coduri Unicode. Codurile Unicode pentru emoji-ul inimii sunt `"U+2764 U+FE0F"`. Acestea sunt întotdeauna aceleași pentru aceleași emoji-uri, așa că comparăm două șiruri identice între ele, ceea ce returnează + +

+
+ +--- + +###### 108. Care dintre aceste metode modifică array-ul original? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `Toate` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Răspuns +

+ +#### Răspuns: D + +Cu metoda `splice` mmodificăm array-ul original prin ștergerea, înlocuirea sau adăugarea de elemente. În acest caz, am eliminat 2 elemente de la indexul 1 (am eliminat `'🥑'` și `'😍'`) și am adăugat emoji-ul ✨ în locul lor. + +`map`, `filter` și `slice` returnează un nou array, `find` returnează un element, ia `reduce` returnează o valoare redusă. + +

+
+ +--- + +###### 109. Care este rezultatul? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Am setat valoarea proprietății `favoriteFood` pe obiectul `info` egal cu șirul de caractere cu emoji-ul de pizza, `'🍕'`. Un șir de caractere este un tip de date primitiv. În JavaScript, tipurile de date primitive nu interacționează prin referință. + +În JavaScript, tipurile de date primitive (tot ceea ce nu este obiect) interacționează prin _valoare_. În acest caz, am setat valoarea proprietății `favoriteFood` pe obiectul `info` egală cu valoarea primului element din array-ul `food` care este un șir de caractere cu emoji-ul de pizza în acest caz (`'🍕'`). Un șir de caractere este un tip de date primitiv și interacționează prin valoare (vedeți [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) meu dacă doriți să aflați mai multe). + +Apoi, schimbăm valoarea proprietății `favoriteFood` pe obiectul `info`. Array-ul `food` nu s-a schimbat, deoarece valoarea `favoriteFood` era doar o _copie_ a valorii primului element din array și nu are o referință la aceeași locație în memorie ca elementul din `food[0]`. Când înregistrăm array-ul `food`, acesta rămâne neschimbat, `['🍕', '🍫', '🥑', '🍔']`. + +

+
+ +--- + +###### 110. Ce face această metodă? + +```javascript +JSON.parse(); +``` + +- A: Parcurge JSON-ul pentru a obține o valoare JavaScript +- B: Parcurge un obiect JavaScript pentru a obține un JSON +- C: Parcurge orice valoare JavaScript într-un JSON +- D: Parcurge doar JSON-ul într-un obiect JavaScript + +
Răspuns +

+ +#### Răspuns: A + +Cu metoda `JSON.parse()` putem parsa un șir JSON într-o valoare JavaScript. + +```javascript +// Transformarea unui număr într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Transformarea unei valori de tip array într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Transformarea unui obiect într-un JSON valid, apoi parsarea șirului JSON într-o valoare JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Care este rezultatul? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Fiecare funcție are propriul său _context de execuție_ (sau _domeniu_). Funcția `getName` caută mai întâi în propriul său context (domeniu) pentru a vedea dacă conține variabila `name` pe care încercăm să o accesăm. În acest caz, funcția `getName` conține propria sa variabilă `name` declarăm variabila `name` cu cuvântul cheie `let`, și cu valoarea `'Sarah'`. + +Variabilele declarate cu cuvântul cheie `let` (și `const`) sunt hoisted, dar, spre deosebire de `var`, nu sunt inițializate. Ele nu sunt accesibile înainte de linia în care le declarăm (inițializăm). Acest lucru se numește "zona temporală moartă" (temporal dead zone). Atunci când încercăm să accesăm variabilele înainte de a fi declarate, JavaScript aruncă o eroare de tip `ReferenceError`. + +Dacă nu am fi declarat variabila `name` în interiorul funcției `getName` motorul JavaScript ar fi căutat în josul lanțului de _domenii_. Domeniul exterior are o variabilă numită `name` cu valoarea `Lydia`. În acest caz, ar fi afișat `Lydia`. + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Care este rezultatul? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` și `a` +- B: `a` și `undefined` +- C: `['a', 'b', 'c']` și `a` +- D: `a` și `['a', 'b', 'c']` + +
Răspuns +

+ +#### Răspuns: C + +Cu cuvântul cheie `yield`, cedăm valorile într-o funcție generator. Cu cuvântul cheie `yield*`, putem ceda valori dintr-o altă funcție generator sau dintr-un obiect iterabil (de exemplu, un array). + +În `generatorOne`, folosim cuvântul cheie `yield` pentru a ceda intrega mulțime `['a', 'b', 'c']`. Valoarea proprietății `value` a obiectului returnat de metoda `next` pe obiectul `one` (`one.next().value`) este egală cu întregul array `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +În `generatorTwo`, folosim cuvântul cheie `yield*`. Acest lucru înseamnă că prima valoare cedată din `two`, este egală cu prima valoare cedată din iterator. Iteratorul este mulțimea `['a', 'b', 'c']`. Prima valoare cedată este `a`, așa că prima dată când apelăm `two.next().value`, este returnată valoarea `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Care este rezultatul? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Răspuns +

+ +#### Răspuns: A + +Expresiile din șirurile șablon (template literals) sunt evaluate mai întâi. Acest lucru înseamnă că șirul va conține valoarea returnată de expresie, funcția imediat invocată `(x => x)('I love')` în acest caz. Trecem valoarea `'I love'` ca argument către funcția arrow `x => x`. `x` este egal cu `'I love'`, care este returnată. Aceasta duce la rezultatul `I love to program`. + +

+
+ +--- + +###### 114. Ce se va întâmpla? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: Funcția de callback a `setInterval` nu va fi invocată +- B: Funcția de callback a `setInterval` este invocată o singură dată +- C: Funcția de callback a `setInterval` va fi totuși apelată în fiecare secundă +- D: Nu am apelat niciodată `config.alert()`, config este `null` + +
Răspuns +

+ +#### Răspuns: C + +În mod normal, atunci când setăm obiecte egal cu `null`, acele obiecte sunt _colectate de gunoi_ (garbage collected), deoarece nu mai există nicio referință către acel obiect. Cu toate acestea, deoarece funcția de callback din `setInterval` este o funcție arrow (și, prin urmare, legată de obiectul `config`), funcția de callback încă menține o referință la obiectul `config`. +Atâta timp cât există o referință, obiectul nu va fi colectat de gunoi (garbage collected). +Deoarece aceasta este o intervală de timp, setarea lui `config` la `null` sau `delete` lui `config.alert` nu va colecta intervalul de gunoi și intervalul va continua să fie apelat. +Pentru a-l opri și a-l elimina din memorie, trebuie să folosiți `clearInterval(config.alert)`. +Deoarece acest lucru nu a fost făcut, funcția de callback a `setInterval` va fi în continuare invocată la fiecare 1000 ms (1 secundă). + +

+
+ +--- + +###### 115. Ce metodă(e) va returna valoarea `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 și 3 +- D: Toate + +
Răspuns +

+ +#### Răspuns: B + +Când adăugăm o pereche cheie/valoare folosind metoda `set`, cheia va fi valoarea primului argument transmis funcției `set`, iar valoarea va fi cea de-a doua valoare transmisă funcție `set`. Cheia în acest caz este _funcția_ `() => 'greeting'`, iar valoarea `'Hello world'`. `myMap` este acum `{ () => 'greeting' => 'Hello world!' }`. + +1 este incorect pentru că cheia nu este `'greeting'` ci `() => 'greeting'`. +3 este incorect pentru că creăm o nouă funcție prin transmiterea ei ca parametru către metoda `get`. Obiectele interacționează prin _referință_. Funcțiile sunt obiecte, motiv pentru care două funcții nu sunt niciodată strict egale, chiar dacă sunt identice: ele au o referință către un loc diferit în memorie. + +

+
+ +--- + +###### 116. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Răspuns +

+ +#### Răspuns: C + +Ambele funcții `changeAge` și `changeAgeAndName` au un parametru implicit, și anume un obiect _nou_ creat `{ ...person }`. Acest obiect conține copii ale tuturor cheilor/valorilor din obiectul `person`. + +În primul rând, apelăm funcția `changeAge` și transmitem obiectul `person` ca argument. Această funcție crește valoarea proprietății `age` cu 1. `person` devine `{ name: "Lydia", age: 22 }`. + +Apoi, apelăm funcția `changeAgeAndName`, însă nu transmitem un parametru. În schimb, valoarea lui `x` este egală cu un obiect _nou_: `{ ...person }`. Deoarece este un obiect nou, acesta nu afectează valorile proprietăților din obiectul `person`. `person` rămâne egal cu `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 117. Care dintre opțiunile următoare va returna `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Răspuns +

+ +#### Răspuns: C + +Cu operatorul spread `...`, putem _răspândi_ obiecte iterabile în elemente individuale. Funcția `sumValues` primește trei argumente: `x`, `y` și `z`. `...[1, 2, 3]` va rezulta în `1, 2, 3`, pe care le transmitem funcției `sumValues`. + +

+
+ +--- + +###### 118. Care este rezultatul? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu operandul `+=` incrementăm valoarea lui `num` cu `1`. Inițial, `num` avea valoarea `1`, deci `1 + 1` este `2`. Elementul de pe al doilea index în mulțimea `list` este 🥰, `console.log(list[2])` va afișa 🥰. + +

+
+ +--- + +###### 119. Care este rezultatul? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cu operatorul de verificare opțională `?.`, nu mai este necesar să verificăm explicit dacă valorile mai profunde încorporate sunt valide sau nu. Dacă încercăm să accesăm o proprietate pe o valoare `undefined` sau `null` valoarea (_nullish_), expresia face un scurtcircuit și returnează `undefined`. + +`person.pet?.name`: `person` are o proprietate numită `pet`: `person.pet` nu este `nullish`. Are o proprietate numită `name`, și returnează `Mara`. +`person.pet?.family?.name`: `person` are o proprietate numită `pet`: `person.pet` nu este `nullish`. `pet` _nu_ are o proprietate numită `family`, `person.pet.family` este `nullish`. Expresia returnează `undefined`. +`person.getFullName?.()`: `person` are o proprietate `getFullName`: `person.getFullName()` nu este `nullish` și poate fi invocată, care returnează `Lydia Hallie`. +`member.getLastName?.()`: variabila `member` nu există, prin urmare se va genera o excepție de tip `ReferenceError` gets thrown! + +

+
+ +--- + +###### 120. Care este rezultatul? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Răspuns +

+ +#### Răspuns: B + +Am trecut condiția `groceries.indexOf("banana")` în instrucțiunea `if`. `groceries.indexOf("banana")` returnează `0`, care este o valoare falsă. Deoarece condiția din instrucțiunea `if` este falsă, se execută codul din blocul `else`, și `We don't have to buy bananas!` se afișează. + +

+
+ +--- + +###### 121. Care este rezultatul? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `language` este un `setter`. Setter-urile nu rețin o valoare reală; scopul lor este să _modifice_ proprietăți. Atunci când apelați o metodă `setter`, aceasta va returna `undefined`. + +

+
+ +--- + +###### 122. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Răspuns +

+ +#### Răspuns: C + +`typeof name` returnează `"string"`. Șirul de caractere `"string"` este o valoare adevărată (truthy), așa că `!typeof name` returnează valoarea booleană `false`. `false === "object"` și `false === "string"` ambele returnează `false`. + +(Dacă dorim să verificăm dacă tipul este (ne)egal cu un anumit tip, ar trebui să folosim `!==` în loc de `!typeof`) + +

+
+ +--- + +###### 123. Care este rezultatul? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `add` returnează o funcție arrow, care returnează o altă funcție arrow, care la rândul ei returnează o altă funcție arrow (încă sunteți cu mine?). Prima funcție primește un argument `x` cu valoarea `4`. Apelăm a doua funcție, care primește un argument `y` cu valoarea `5`. Apoi apelăm a treia funcție, care primește un argument `z` cu valoarea `6`. Când încercăm să accesăm valorile `x`, `y` și `z` în ultima funcție arrow, motorul JavaScript urcă lanțul de domenii pentru a găsi valorile pentru `x` și `y` în consecință. Aceasta returnează `4` `5` `6`. + +

+
+ +--- + +###### 124. Care este rezultatul? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: C + +Funcția generator `range` returnează un obiect asincron cu promisiuni pentru fiecare element din intervalul pe care îl transmitem: `Promise{1}`, `Promise{2}`, `Promise{3}`. Setăm variabila `gen` egală cu obiectul asincron, după care facem o buclă peste el folosind o buclă `for await ... of`. Setăm variabila `item` eegală cu valorile promisiunilor returnate: mai întâi `Promise{1}`, apoi `Promise{2}`, apoi `Promise{3}`. Deoarece _așteptăm_ valoarea lui `item`, adică promisiunea rezolvată, _valorile_ rezolvate ale promisiunilor sunt returnate: `1`, `2`, apoi `3`. + +

+
+ +--- + +###### 125. Care este rezultatul? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Răspuns +

+ +#### Răspuns: D + +`myFunc` așteaptă ca argument un obiect cu proprietățile `x`, `y` și `z`. Deoarece transmitem doar trei valori numerice separate (1, 2, 3) în loc de un obiect cu proprietățile `x`, `y` și `z` ({x: 1, y: 2, z: 3}), `x`, `y` și `z` primesc valoarea lor implicită, care este `undefined`. + +

+
+ +--- + +###### 126. Care este rezultatul? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `Șoferul a condus ${formattedSpeed} și trebuie să plătească ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: Șoferul a condus 130 și trebuie să plătească 300 +- B: Șoferul a condus 130 mph și trebuie să plătească \$300.00 +- C: Șoferul a condus undefined și trebuie să plătească undefined +- D: Șoferul a condus 130.00 și trebuie să plătească 300.00 + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `Intl.NumberFormat` putem formata valorile numerice în orice locație. Formatez valoarea numerică `130` pentru locația `en-US` ca o `unitate` în `mile-per-hour`, ceea ce rezultă în `130 mph`. Valoarea numerică `300` pentru locația `en-US` ca `monedă` în `USD` rezultă în `$300.00`. + +

+
+ +--- + +###### 127. Care este rezultatul? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Răspuns +

+ +#### Răspuns: B + +Prin destrucțurarea obiectelor, putem extrage valorile din obiectul din partea dreaptă și le atribui valorii cu același nume de proprietate din obiectul din partea stângă. În acest caz, atribuim valoarea "💀" lui `spookyItems[3]`. Acest lucru înseamnă că modificăm array-ul `spookyItems`, adăugăm "💀" la el. La afișarea în consolă a lui `spookyItems`, se va afișa `["👻", "🎃", "🕸", "💀"]`. + +

+
+ +--- + +###### 128. Care este rezultatul? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Răspuns +

+ +#### Răspuns: C + +Cu metoda `Number.isNaN` puteți verifica dacă valoarea pe care o transmiteți este o _valoare numerică_ și este egală cu `NaN`. `name` nu este o valoare numerică, așa că `Number.isNaN(name)` returnează `false`. `age` este o valoare numerică, dar nu este egală cu `NaN`, astfel că `Number.isNaN(age)` returnează `false`. + +Cu metoda `isNaN` puteți verifica dacă valoarea pe care o transmiteți nu este un număr. `name` nu este un număr, așa că `isNaN(name)` returnează `true`. `age` este un număr, astfel că `isNaN(age)` returnează `false`. + +

+
+ +--- + +###### 129. Care este rezultatul? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: D + +Variabilele declarate cu cuvântul cheie `const` nu pot fi referite înainte de inițializare: acest lucru se numește _zona temporală moartă_ (temporal dead zone). În funcția `getInfo`, variabila`randomValue` este de domeniu în domeniul funcțional al funcției `getInfo`. Pe linia în care dorim să afișăm valoarea `typeof randomValue`, variabila `randomValue` nu este încă inițializată: se va genera o eroare de tip `ReferenceError`! Motorul nu a căutat în josul lanțului de domenii deoarece am declarat variabila `randomValue` în funcția `getInfo`. + +

+
+ +--- + +###### 130. Care este rezultatul? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Răspuns +

+ +#### Răspuns: C + +În blocul `try` înregistrăm valoarea așteptată a variabilei `myPromise`: `"Woah some cool data"`. Deoarece nu s-au generat erori în blocul `try` codul din blocul `catch` nu se execută. Codul din blocul `finally` se execută _întotdeauna_, și se va afișa `"Oh finally!"`. + +

+
+ +--- + +###### 131. Care este rezultatul? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Răspuns +

+ +#### Răspuns: B + +Cu metoda `flat` putem crea un nou array aplatizat. Adâncimea array-ului aplatizat depinde de valoarea pe care o transmitem. În acest caz, am transmis valoarea `1` (care nu era necesară, deoarece aceasta este valoarea implicită), ceea ce înseamnă că vor fi concatenate doar array-urile de pe primul nivel de adâncime. `['🥑']` și `['✨', '✨', ['🍕', '🍕']]`. Concatenarea acestor două array-uri rezultă în `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Care este rezultatul? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Răspuns +

+ +#### Răspuns: D + +`counterOne` este o instanță a clasei `Counter`. Clasa `Counter` conține o proprietate `count` în constructorul său și o metodă `increment`. Mai întâi, am invocat metoda `increment` de două ori, apelând `counterOne.increment()`. În prezent, `counterOne.count` este `2`. + + + +Apoi, creăm o nouă variabilă `counterTwo`, și o setăm egală cu `counterOne`. Deoarece obiectele interacționează prin referință, creăm doar o nouă referință către același loc în memorie la care indică `counterOne`. Deoarece au același loc în memorie, orice modificări făcute asupra obiectului la care `counterTwo` are o referință se aplică și la `counterOne`. În prezen, `counterTwo.count` este `2`. + +Apelăm `counterTwo.increment()`, ceea ce setează `count` la `3`. Apoi, afișăm valoarea lui `counterOne`, ceea ce va afișa `3`. + + + +

+
+ +--- + +###### 133. Care este rezultatul? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Răspuns +

+ +#### Răspuns: C + +În primul rând, apelăm `funcOne`. Pe prima linie a lui `funcOne`, apelăm funcția _asincronă_ `setTimeout`, din care funcția de apel se trimite către API-ul Web. (vezi articolul meu despre bucla evenimentelor aici.) + +Apoi apelăm promisiunea `myPromise` care este o operațiune _asincronă_. + +Ambele promisiuni și întârzierile (timeout) sunt operațiuni asincrone, iar funcția continuă să ruleze în timp ce finalizează promisiunea și gestionează apelul de întârziere `setTimeout`. Acest lucru înseamnă că se va afișa mai întâi `Last line 1!`, deoarece aceasta nu este o operațiune asincronă. + +Deoarece stiva de apel nu este încă goală, funcția `setTimeout` și promisiunea din `funcOne` nu pot fi adăugate încă la stiva de apel. + +În `funcTwo`, variabila `res` primește o `Promise` pentru că `Promise.resolve(Promise.resolve('Promise'))` este echivalent cu `Promise.resolve('Promise')` deoarece rezolvarea unei promisiuni rezolvă doar valoarea acesteia. Cuvântul cheie `await` din această linie oprește execuția funcției până când primește rezoluția promisiunii și apoi continuă să ruleze sincron până la finalizare, așa că sunt afișate `Promise 2!` apoi `Last line 2!` iar apelul `setTimeout` este trimis către API-ul Web. + +Apoi stiva de apel este goală. Promisiunile sunt _microtask-uri_ astfel că sunt rezolvate în primul rând atunci când stiva de apel este goală, așa că se afișează `Promise 1!`. + +Acum, deoarece `funcTwo` pa fost scoasă din stiva de apel, stiva de apel este goală. Callback-urile așteptând în coadă (`() => console.log("Timeout 1!")` din `funcOne`, și `() => console.log("Timeout 2!")` din `funcTwo`) sunt adăugate pe stivă unul câte unul. Primul callback afișează `Timeout 1!`, și este eliminat din stivă. Apoi, al doilea callback afișează `Timeout 2!`, și este eliminat din stivă. + +

+
+ +--- + +###### 134. Cum putem apela funcția `sum` în `sum.js` din `index.js`? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Exporturile implicite nu sunt importate cu `*`, doar exporturile numite + +
Răspuns +

+ +#### Răspuns: C + +Cu asteriscul `*`, importăm toate valorile exportate din acel fișier, atât exporturile implicite, cât și cele numite. Dacă avem următorul fișierȘ + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +Acesta ar fi rezultatul înregistrărilor: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Pentru exemplul cu funcția `sum`, înseamnă că valoarea importată `sum` arată în felul următor: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Putem invoca această funcție, apelând `sum.default` + +

+
+ +--- + +###### 135. Care este rezultatul? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Nu se înregistrează nimic + +
Răspuns +

+ +#### Răspuns: C + +Cu un obiect Proxy, putem adăuga comportament personalizat unui obiect pe care îl transmitem ca al doilea argument. În acest caz, transmitem obiectul `handler` care conține două proprietăți: `set` și `get`. `set` este invocată ori de câte ori _set_ (setăm) valori de proprietate, `get` este invocată ori de câte ori _get_ (accesăm) valori de proprietate. + +Primul argument este un obiect gol `{}`, care este valoarea lui `person`. La acest obiect, se adaugă comportamentul personalizat specificat în obiectul `handler`. Dacă adăugăm o proprietate la obiectul `person`, `set` va fi invocată. Dacă accesăm o proprietate a obiectului `person`, `get` va fi invocată. + +În primul rând, am adăugat o nouă proprietate `name` la obiectul proxy (`person.name = "Lydia"`). `set` este invocată și înregistrează mesajul `"Added a new property!"`. + +Then, we access a property value on the proxy object, the `get` property on the handler object got invoked. `"Accessed a property!"` gets logged. + +

+
+ +--- + +###### 136. Care dintre următoarele va modifica obiectul `person`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Răspuns +

+ +#### Răspuns: A + +Cu `Object.seal` putem preveni _adăugarea_ de noi proprietăți sau _eliminarea_ proprietăților existente. + +Cu toate acestea, puteți încă să modificați valoarea proprietăților existente. + +

+
+ +--- + +###### 137. Care dintre următoarele va modifica obiectul `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Răspuns +

+ +#### Răspuns: C + +Metoda `Object.freeze` _îngheață_ un obiect. Nu se pot adăuga, modifica sau elimina proprietăți. + +Cu toate acestea, aceasta îngheață obiectul doar în mod _superficial_, ceea ce înseamnă că numai proprietățile _directe_ ale obiectului sunt înghețate. Dacă proprietatea este un alt obiect, cum ar fi `address` în acest caz, proprietățile de pe acel obiect nu sunt înghețate și pot fi modificate. + +

+
+ +--- + +###### 138. Care este rezultatul? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` și `3` `6` +- B: `2` `NaN` și `3` `NaN` +- C: `2` `Error` și `3` `6` +- D: `2` `4` și `3` `Error` + +
Răspuns +

+ +#### Răspuns: A + +În primul rând, am apelat `myFunc()` fără a transmite niciun argument. Deoarece nu am transmis argumente, `num` și `value` au primit valorile lor implicite: `num` este `2`, și `value` este valoarea returnată de funcția `add`. Funcției `add` îi transmitem `num` ca argument, care avea valoarea `2`. `add` returnează `4`, care este valoarea lui `value`. + +Apoi, am apelat `myFunc(3)` și am transmis valoarea `3` ca valoare pentru argumentul `num`. Nu am transmis un argument pentru `value`. Deoarece nu am transmis o valoare pentru argumentul `value` acesta a primit valoarea implicită: valoarea returnată de funcția `add`. Funcției `add`, îi transmitem `num`, care are valoarea `3`. `add` returnează `6`, care este valoarea lui `value`. + +

+
+ +--- + +###### 139. Care este rezultatul? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Răspuns +

+ +#### Răspuns: D + +În ES2020, putem adăuga variabile private în clase folosind simbolul `#`. Nu putem accesa aceste variabile în afara clasei. Atunci când încercăm să înregistrăm `counter.#number`, se aruncă o eroare de sintaxă (SyntaxError): nu putem accesa această variabilă în afara clasei `Counter`! + +

+
+ +--- + +###### 140. Ce lipsește? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Răspuns +

+ +#### Răspuns: B + +Pentru a itera prin `membrii` din fiecare element din array-ul `members` trebuie să transmitem `teams[i].members` către funcția generator `getMembers`. Funcția generator returnează un obiect generator. Pentru a itera prin fiecare element din acest obiect generator, trebuie să folosim `yield*`. + +Dacă am fi scris `yield`, `return yield`, sau `return`, întreaga funcție generator ar fi fost returnată prima dată când am apelat metoda `next`. + +

+
+ +--- + +###### 141. Care este rezultatul? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Răspuns +

+ +#### Răspuns: C + +Funcția `addHobby` primește două argumente, `hobby` și `hobbies` cu valoarea implicită a array-ului `hobbies` din obiectul `person`. + +În primul rând, apelăm funcția `addHobby`, și transmitem `"running"` ca valoare pentru `hobby` și un array gol ca valoare pentru `hobbies`. Deoarece transmitem un array gol ca valoare pentru `hobbies`, `"running"` este adăugat la acest array gol. + +Apoi, apelăm funcția `addHobby` și transmitem `"dancing"` ca valoare pentru `hobby`. Nu am transmis o valoare pentru `hobbies`, astfel că aceasta primește valoarea implicită, adică proprietatea `hobbies` din obiectul `person`. Adăugăm hobby-ul `dancing` în array-ul `person.hobbies`. + +În final, apelăm funcția `addHobby`, și transmitem `"baking"` ca valoare pentru `hobby`, și array-ul `person.hobbies` ca valoare pentru `hobbies`. Adăugăm hobby-ul `baking` în array-ul `person.hobbies`. + +După adăugarea lui `dancing` și `baking`, valoarea lui `person.hobbies` este `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Care este rezultatul? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nimic, nu am apelat la nicio metodă + +
Răspuns +

+ +#### Răspuns: B + +Creăm variabila `pet` care este o instanță a clasei `Flamingo`. Când instantiem această instanță, `constructor` din clasa `Flamingo` este apelat. Mai întâi, se înregistrează `"I'm pink. 🌸"` după care apelăm `super()`. `super()` apelează constructorul clasei părinte, `Bird`. Constructorul din clasa `Bird` este apelat și înregistrează `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Care dintre opțiuni rezultă într-o eroare? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 și 2 +- C: 3 și 4 +- D: 3 + +
Răspuns +

+ +#### Răspuns: D + +Cuvântul cheie `const` înseamnă pur și simplu că nu putem _redeclara_ valoarea acelei variabile, aceasta este _numai pentru citire_ (read-only). Cu toate acestea, valoarea în sine nu este imutabilă. Proprietățile din array-ul `emojis` pot fi modificate, de exemplu, prin adăugarea de valori noi, prin decuparea lor sau prin setarea lungimii array-ului la 0. + +

+
+ +--- + +###### 144. Ce trebuie să adăugăm la obiectul `person` pentru a obține `["Lydia Hallie", 21]` ca rezultat al `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Nimic, obiectele sunt iterabile în mod implicit +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Răspuns +

+ +#### Răspuns: C + +Obiectele nu sunt iterabile în mod implicit. Un obiect devine iterabil atunci când protocolul iterator este prezent. Putem adăuga acest protocol manual prin adăugarea simbolului iterator `[Symbol.iterator]`, care trebuie să returneze un obiect generator, de exemplu, prin definirea unei funcții generator `*[Symbol.iterator]() {}`. Această funcție generator trebuie să furnizeze `Object.values` ale obiectulu `person` pentru a obține array-ul `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Care este rezultatul? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Răspuns +

+ +#### Răspuns: C + +Condiția `if` din interiorul buclei `forEach` verifică dacă valoarea lui `num` este adevărată (truthy) sau falsă (falsy). Deoarece primul număr din array-ul `nums` este `0`, o valoare falsă, blocul de cod al instrucțiunii `if` nu va fi executat. `count` se incrementează doar pentru celelalte 3 numere din array-ul `nums`, adică `1`, `2` și `3`. Deoarece `count` se incrementează cu `1` de 3 ori, valoarea lui `count` este `3`. + +

+
+ +--- + +###### 146. Care este rezultatul? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Răspuns +

+ +#### Răspuns: D + +Simbolul `?` ne permite să accesăm opțional proprietăți mai adânc în obiecte. Încercăm să înregistrăm elementul de pe indexul `1` din sub-array-ul de pe indexul `1` al array-ului `fruits`. Dacă sub-array-ul de pe indexul `1` din array-ul `fruits` nu există, va returna pur și simplu `undefined`. Dacă sub-array-ul de pe indexul `1` din array-ul `fruits` există, dar acest sub-array nu are un element pe indexul `1` va returna, de asemenea, `undefined`. + +În primul rând, încercăm să înregistrăm al doilea element din sub-array-ul`['🍍']` din `[['🍊', '🍌'], ['🍍']]`. Acest sub-array conține doar un singur element, ceea ce înseamnă că nu există niciun element pe indexul `1`, și va returna `undefined`. + +Apoi, apelăm funcția `getFruits` fără a transmite o valoare ca argument, ceea ce înseamnă că `fruits` are implicit o valoare de `undefined`. Deoarece facem o verificare condițională pentru accesarea elementului de pe indexul `1` al `fruits`, aceasta va returna `undefined` deoarece acest element de pe indexu `1` nu există. + +În cele din urmă, încercăm să înregistrăm al doilea element din sub-array-ul `['🍊', '🍌']` din `['🍍'], ['🍊', '🍌']`. Elementul de pe indexul `1` în acest sub-array este `🍌`, are este înregistrat. + +

+
+ +--- + +###### 147. Care este rezultatul? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Am setat variabila `calc` gal cu o nouă instanță a clasei `Calc`. Apoi, am creat o altă instanță nouă a clasei `Calc`, și am apelat metoda `increase` pe această instanță. Deoarece proprietatea `count` se află în constructorul clasei `Calc`, proprietatea `count` nu este partajată în prototipul clasei `Calc`. Acest lucru înseamnă că valoarea lui `count` nu a fost actualizată pentru instanța către care arată `calc` astfel încât `count` rămâne `0`. + +

+
+ +--- + +###### 148. Care este rezultatul? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Funcția `updateUser` actualizează valorile proprietăților `email` și `password` ale obiectului `user`, dacă aceste valori sunt transmise funcției, după care funcția returnează obiectul `user`. Valoarea returnată a funcției `updateUser` este obiectul `user`, ceea ce înseamnă că valoarea lui `updatedUser` este o referință către același obiect `user` la care face referință și `user`. `updatedUser === user` este egal cu `true`. + +

+
+ +--- + +###### 149. Care este rezultatul? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Răspuns +

+ +#### Răspuns: C + +În primul rând, apelăm metoda `slice` pe array-ul `fruit`. Metoda `slice` nu modifică array-ul original, ci returnează valoarea pe care a tăiat-o din array: emoji-ul de banană. +Apoi, apelăm metoda `splice` pe array-ul `fruit`. Metoda `splice` modifică array-ul original, ceea ce înseamnă că array-ul `fruit` acum conține `['🍊', '🍎']`. +În cele din urmă, apelăm metoda `unshift` pe array-u `fruit`, care modifică array-ul original prin adăugarea valorii furnizate, în acest caz, ‘🍇’ ca prim element în array. Array-ul `fruit` acum conține `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Care este rezultatul? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: B + +Cheile obiectelor sunt convertite în șiruri de caractere. + +Deoarece valoarea lui `dog` este un obiect, `animals[dog]` înseamnă de fapt că creăm o nouă proprietate numită `"object Object"` egală cu noul obiect. `animals["object Object"]` este acum egal cu `{ emoji: "🐶", name: "Mara"}`. + +`cat` este, de asemenea, un obiect, ceea ce înseamnă că `animals[cat]` înseamnă de fapt că suprascriem valoarea lui `animals["object Object"]` cu noile proprietăți ale pisicii. + +Înregistrarea `animals[dog]`, sau mai exact `animals["object Object"]` deoarece convertirea obiectului `dog` într-un șir rezultă în `"object Object"`, returnează `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Care este rezultatul? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Răspuns +

+ +#### Răspuns: A + +Funcția `updateEmail` este o funcție săgeată și nu este legată de obiectul `user`. Acest lucru înseamnă că cuvântul cheie `this` nu se referă la obiectul `user`, ci se referă la domeniul global în acest caz. Valoarea `email` din obiectul `user` nu se actualizează. Când se înregistrează valoarea `user.email`, se returnează valoarea originală `my@email.com`. + +

+
+ +--- + +###### 152. Care este rezultatul? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Răspuns +

+ +#### Răspuns: D + +Metoda `Promise.all` rulează promisiunile transmise în paralel. Dacă o promisiune eșuează, metoda `Promise.all` se _respinge_ cu valoarea promisiunii respinse. În acest caz, `promise3` a fost respinsă cu valoarea `"Third"`. Prindem valoarea respinsă în metoda `catch` lantată în invocarea `runPromises` pentru a prinde orice erori din interiorul funcției `runPromises`. Se înregistrează doar `"Third"` deoarece `promise3` a fost respinsă cu această valoare. + +

+
+ +--- + +###### 153. Ce valoare ar trebui să aibă `method` pentru a înregistra `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Răspuns +

+ +#### Răspuns: C + +Metoda `fromEntries` transformă o matrice 2D într-un obiect. Primul element din fiecare submatrice va fi cheia, iar al doilea element din fiecare submatrice va fi valoarea. În acest caz, facem mapare peste matricea `keys` care returnează o matrice în care primul element este elementul din matricea cheilor la indexul curent, iar al doilea element este elementul din matricea valorilor la indexul curent. + +Acest lucru creează o matrice de submatrici care conțin cheile și valorile corecte, rezultând în `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Care este rezultatul? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Răspuns +

+ +#### Răspuns: C + +Valoarea implicită a lui `address` este un obiect gol `{}`. Când setăm variabila `member` egală cu obiectul returnat de funcția `createMember`, nu am transmis o valoare pentru `address`, ceea ce înseamnă că valoarea lui `address` este obiectul gol implicit `{}`. Un obiect gol este o valoare adevărată (truthy), ceea ce înseamnă că condiția din expresia ternară `address ? address : null` returnează `true`. Prin urmare, valoarea lui `address` este obiectul gol `{}`. + +

+
+ +--- + +###### 155. Care este rezultatul? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Răspuns +

+ +#### Răspuns: B + +Condiția din instrucțiunea `if` verifică dacă valoarea lui `!typeof randomValue` este egală cu `"string"`. Operatorul `!` convertește valoarea la o valoare booleană. Dacă valoarea este adevărată (truthy), valoarea returnată va fi `false`, iar dacă valoarea este falsă (falsy), valoarea returnată va fi `true`. În acest caz, valoarea returnată de `typeof randomValue` este valoarea adevărată (truthy) `"number"`, ceea ce înseamnă că valoarea lui `!typeof randomValue` este valoarea booleană `false`. + +`!typeof randomValue === "string"` întotdeauna returnează `false`, deoarece de fapt verificăm `false === "string"`. Deoarece condiția returnează `false`, blocul de cod al instrucțiunii `else` se execută, iar `Yay it's a string!` este înregistrat. + +

+
diff --git a/ru-RU/README.md b/ru-RU/README.md index eb6be283..ace3f67a 100644 --- a/ru-RU/README.md +++ b/ru-RU/README.md @@ -1,34 +1,50 @@ -# Список (продвинутых) вопросов по JavaScript +
+ +

Вопросы по JavaScript

-Я ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder), которые дублируются в этом репозитории. +--- + +Я (Lydia Hallie) ежедневно публикую вопросы по JavaScript с вариантами ответов в своем [Instagram](https://www.instagram.com/theavocoder) **сторис**, которые дублируются в этом репозитории! Последнее обновление: 12 июня. -От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я обновляю репозиторий еженедельно новыми вопросами. Последнее обновление: 9 октября. +От базового до продвинутого: проверьте, насколько хорошо вы знаете JavaScript, немного освежите свои знания или подготовьтесь к собеседованию! :muscle: :rocket: Я регулярно обновляю этот репозиторий новыми вопросами. Ответы находятся в **свернутой секции** под каждым вопросом. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: + +Не стесняйтесь обращаться ко мне (Lydia Hallie)! 😊
+Instagram || Twitter || LinkedIn || Blog +
-Ответы находятся в свернутой секции ниже вопросов. Просто нажми на "Ответ", чтобы развернуть. Удачи! :heart: +| Не стесняйтесь использовать эти примеры в проектах! 😃 Я (Lydia Hallie) была бы _действительно_ признателена за ссылку на этот репозиторий. Я добавляю вопросы и объяснения, и сообщество очень помогает мне поддерживать и улучшать все это! 💪🏼 Спасибо и приятного просмотра! | +|---| -Хотите получать электронную почту всякий раз, когда я добавляю новые вопросы?
-✨✉Подпишитесь на обновления✉✨ +--- +
Доступно в 20 переводах 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

-Список доступных переводов: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇬🇧 English](../README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) +

+
--- @@ -105,8 +121,8 @@ const shape = { perimeter: () => 2 * Math.PI * this.radius }; -shape.diameter(); -shape.perimeter(); +console.log(shape.diameter()); +console.log(shape.perimeter()); ``` - A: `20` и `62.83185307179586` @@ -119,7 +135,7 @@ shape.perimeter(); #### Ответ: B -Заметь, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция. +Заметьте, что `diameter` это обычная функция, в то время как `perimeter` это стрелочная функция. У стрелочных функций значение `this` указывает на окружающую область видимости, в отличие от обычных функций! Это значит, что при вызове `perimeter` значение `this` у этой функции указывает не на объект `shape`, а на внешнюю область видимости (например, window). @@ -134,7 +150,7 @@ shape.perimeter(); ```javascript +true; -!"Lydia"; +!'Lydia'; ``` - A: `1` и `false` @@ -159,11 +175,11 @@ shape.perimeter(); ```javascript const bird = { - size: "small" + size: 'small' }; const mouse = { - name: "Mickey", + name: 'Mickey', small: true }; ``` @@ -191,15 +207,14 @@ JavaScript интерпретирует (или распаковывает) оп --- - ###### 6. Что будет в консоли? ```javascript -let c = { greeting: "Hey!" }; +let c = { greeting: 'Hey!' }; let d; d = c; -c.greeting = "Hello"; +c.greeting = 'Hello'; console.log(d.greeting); ``` @@ -220,7 +235,7 @@ console.log(d.greeting); -Когда ты изменяешь один объект, то изменяются значения всех ссылок, указывающих на этот объект. +Когда вы изменяете один объект, то изменяются значения всех ссылок, указывающих на этот объект.

@@ -249,7 +264,7 @@ console.log(b === c); #### Ответ: C -`new Number()` это встроенный конструктор функции. И хотя он выглядит как число, это не настоящее число: у него есть ряд дополнительных фич и это объект. +`new Number()` это встроенный конструктор функции. И хотя он выглядит как число, это не настоящее число: у него есть ряд дополнительных особеннстей, и это объект. Оператор `==` разрешает приведение типов, он проверяет равенство _значений_. Оба значения равны `3`, поэтому возвращается `true`. @@ -269,13 +284,13 @@ class Chameleon { return this.newColor; } - constructor({ newColor = "green" } = {}) { + constructor({ newColor = 'green' } = {}) { this.newColor = newColor; } } -const freddie = new Chameleon({ newColor: "purple" }); -freddie.colorChange("orange"); +const freddie = new Chameleon({ newColor: 'purple' }); +freddie.colorChange('orange'); ``` - A: `orange` @@ -288,7 +303,7 @@ freddie.colorChange("orange"); #### Ответ: D -Функция `colorChange` является статичной. Статичные методы не имеют доступа к экземплярам класса. Так как `freddie` это экземпляр, то статичный метод там не доступен. Поэтому выбрасывается ошибка `TypeError`. +Функция `colorChange` является статической. Статические методы предназначены для работы только в конструкторе, в котором они созданы, и не могут передаваться каким-либо дочерним элементам или вызываться в экземплярах класса. Так как `freddie` является экземпляром класса `Chameleon`, функция не может быть вызвана для него. Будет выдана ошибка `TypeError`.

@@ -312,7 +327,12 @@ console.log(greetign); #### Ответ: A -В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле выполнил `global.greetign = {}` (или `window.greetign = {}` в браузере). +В консоли выведется объект, потому что мы только что создали пустой объект в глобальном объекте! Когда мы вместо `greeting` написали `greetign`, интерпретатор JS на самом деле увидел: + +1. `global.greetign = {}` в Node.js +2. `window.greetign = {}`, `frames.geetign = {}` и `self.greetign` в браузерах. +3. `self.greetign` в веб-воркерах. +4. `globalThis.greetign` во всех окружениях. Нужно использовать `"use strict"`, чтобы избежать такого поведения. Эта запись поможет быть уверенным в том, что переменная была определена перед тем как ей присвоили значение. @@ -325,10 +345,10 @@ console.log(greetign); ```javascript function bark() { - console.log("Woof!"); + console.log('Woof!'); } -bark.animal = "dog"; +bark.animal = 'dog'; ``` - A: Ничего, всё в порядке! @@ -358,7 +378,7 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const member = new Person("Lydia", "Hallie"); +const member = new Person('Lydia', 'Hallie'); Person.getFullName = function () { return `${this.firstName} ${this.lastName}`; } @@ -376,7 +396,9 @@ console.log(member.getFullName()); #### Ответ: A -Нельзя добавлять свойства конструктору, как обычному объекту. Если нужно добавить фичу всем объектам, то необходимо использовать прототипы. В данном случае +В JavaScript функции являются объектами, поэтому метод `getFullName` добавляется к самому объекту функции-конструктора. По этой причине мы можем вызвать `Person.getFullName()`, но `member.getFullName` выдает `TypeError`. + +Если вы хотите, чтобы метод был доступен для всех экземпляров объекта, вы должны добавить его в свойство прототипа: ```js Person.prototype.getFullName = function () { @@ -384,8 +406,6 @@ Person.prototype.getFullName = function () { } ``` -сделает метод `member.getFullName()` рабочим. В чем тут преимущество? Предположим, что мы добавили этот метод к конструктору. Возможно, не каждому экземпляру `Person` нужен этот метод. Это приведет к большим потерям памяти, т.к. все экземпляры будут иметь это свойство. Напротив, если мы добавим этот метод только к прототипу, у нас будет только одно место в памяти, к которому смогут обращаться все экземпляры! -

@@ -399,8 +419,8 @@ function Person(firstName, lastName) { this.lastName = lastName; } -const lydia = new Person("Lydia", "Hallie"); -const sarah = Person("Sarah", "Smith"); +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); console.log(lydia); console.log(sarah); @@ -456,7 +476,7 @@ console.log(sarah); #### Ответ: B -Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект имеет доступ до некоторых методов и свойств, таких как `.toString`. Именно поэтому мы можем использовать встроенные методы JavaScript! Все эти методы доступны в прототипе. Если JavaScript не может найти метод непосредственно у объекта, он продолжает поиск по цепочке прототипов пока не найдет. +Все объекты имеют прототипы, кроме **базового объекта**. Базовый объект — это объект, созданный пользователем, или объект, созданный с использованием ключевого слова `new`. Базовый объект имеет доступ к некоторым методам и свойствам, таким как `.toString`. Вот почему вы можете использовать встроенные методы JavaScript! Все такие способы доступны в прототипе. Хотя JavaScript не может найти метод непосредственно в вашем объекте, он идет вниз по цепочке прототипов и находит его там, что делает его доступным.

@@ -470,7 +490,7 @@ function sum(a, b) { return a + b; } -sum(1, "2"); +sum(1, '2'); ``` - A: `NaN` @@ -537,7 +557,7 @@ function getPersonInfo(one, two, three) { console.log(three); } -const person = "Lydia"; +const person = 'Lydia'; const age = 21; getPersonInfo`${person} is ${age} years old`; @@ -552,7 +572,7 @@ getPersonInfo`${person} is ${age} years old`; #### Ответ: B -При использовании тегированных шаблонных литералов первым аргументом всегда будет массив строковых значений. Оставшимися аргументами будут значения переданных выражений! +При использовании [шаблонных строк](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Template_literals) первым аргументом всегда будет массив строковых значений. Оставшимися аргументами будут значения переданных выражений!

@@ -564,9 +584,9 @@ getPersonInfo`${person} is ${age} years old`; ```javascript function checkAge(data) { if (data === { age: 18 }) { - console.log("Ты взрослый!"); + console.log('Ты взрослый!'); } else if (data == { age: 18 }) { - console.log("Ты все еще взрослый."); + console.log('Ты все еще взрослый.'); } else { console.log(`Хмм.. Кажется, у тебя нет возраста.`); } @@ -626,7 +646,7 @@ getAge(21); ```javascript function getAge() { - "use strict"; + 'use strict'; age = 21; console.log(age); } @@ -654,7 +674,7 @@ getAge(); ###### 21. Чему будет равно `sum`? ```javascript -const sum = eval("10*10+5"); +const sum = eval('10*10+5'); ``` - A: `105` @@ -677,7 +697,7 @@ const sum = eval("10*10+5"); ###### 22. Как долго будет доступен cool_secret? ```javascript -sessionStorage.setItem("cool_secret", 123); +sessionStorage.setItem('cool_secret', 123); ``` - A: Всегда, данные не потеряются. @@ -730,12 +750,12 @@ console.log(num); ###### 24. Каким будет результат? ```javascript -const obj = { 1: "a", 2: "b", 3: "c" }; +const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); -obj.hasOwnProperty("1"); +obj.hasOwnProperty('1'); obj.hasOwnProperty(1); -set.has("1"); +set.has('1'); set.has(1); ``` @@ -761,7 +781,7 @@ set.has(1); ###### 25. Что будет в консоли? ```javascript -const obj = { a: "one", b: "two", a: "three" }; +const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj); ``` @@ -786,7 +806,7 @@ console.log(obj); - A: Да - B: Нет -- C: Это зависит +- C: Это зависит от ...
Ответ

@@ -830,12 +850,12 @@ for (let i = 1; i < 5; i++) { ```javascript String.prototype.giveLydiaPizza = () => { - return "Just give Lydia pizza already!"; + return 'Just give Lydia pizza already!'; }; -const name = "Lydia"; +const name = 'Lydia'; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -859,8 +879,8 @@ name.giveLydiaPizza(); ```javascript const a = {}; -const b = { key: "b" }; -const c = { key: "c" }; +const b = { key: 'b' }; +const c = { key: 'c' }; a[b] = 123; a[c] = 456; @@ -892,9 +912,9 @@ console.log(a[b]); ###### 30. Каким будет результат? ```javascript -const foo = () => console.log("First"); -const bar = () => setTimeout(() => console.log("Second")); -const baz = () => console.log("Third"); +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); bar(); foo(); @@ -1001,7 +1021,7 @@ WebAPI не может добавлять содержимое в стек ко ###### 33. Что будет в консоли? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; function sayHi(age) { console.log(`${this.name} is ${age}`); @@ -1037,7 +1057,7 @@ function sayHi() { return (() => 0)(); } -typeof sayHi(); +console.log(typeof sayHi()); ``` - A: `"object"` @@ -1052,7 +1072,8 @@ typeof sayHi(); Функция `sayHi` возвращает значение, возвращаемое из немедленно вызываемого функционального выражения (IIFE). Результатом является `0` типа `"number"`. -Для информации: в JS 7 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, и `symbol`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`. +Для информации: в JS 8 встроенных типов: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol` и `bigint`. `"function"` не является отдельным типом, т.к. функции являются объектами типа `"object"`. +

@@ -1079,14 +1100,16 @@ undefined; #### Ответ: A -Есть только шесть "ложных" значений: +Есть только восемь (8) "ложных" значений: - `undefined` - `null` - `NaN` -- `0` -- `''` (пустая строка) - `false` +- `''` (пустая строка) +- `0` +- `-0` +- `0n` (BigInt(0)) Конструкторы функций, такие как `new Number` и `new Boolean` являются "истинными". @@ -1185,7 +1208,7 @@ console.log(numbers); --- -###### 39. Всё в JavaScript это +###### 39. Всё в JavaScript это... - A: примитив или объект - B: функция или объект @@ -1242,7 +1265,7 @@ console.log(numbers); ```javascript !!null; -!!""; +!!''; !!1; ``` @@ -1267,10 +1290,10 @@ console.log(numbers); --- -###### 42. Что возвращает метод `setInterval`? +###### 42. Что возвращает метод `setInterval` в браузере? ```javascript -setInterval(() => console.log("Hi"), 1000); +setInterval(() => console.log('Hi'), 1000); ``` - A: уникальный id @@ -1293,7 +1316,7 @@ setInterval(() => console.log("Hi"), 1000); ###### 43. Каким будет результат? ```javascript -[..."Lydia"]; +[...'Lydia']; ``` - A: `["L", "y", "d", "i", "a"]` @@ -1352,11 +1375,11 @@ console.log(gen.next().value); ```javascript const firstPromise = new Promise((res, rej) => { - setTimeout(res, 500, "один"); + setTimeout(res, 500, 'один'); }); const secondPromise = new Promise((res, rej) => { - setTimeout(res, 100, "два"); + setTimeout(res, 100, 'два'); }); Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); @@ -1382,7 +1405,7 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); ###### 46. Каким будет результат? ```javascript -let person = { name: "Lydia" }; +let person = { name: 'Lydia' }; const members = [person]; person = null; @@ -1422,7 +1445,7 @@ console.log(members); ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 }; @@ -1451,7 +1474,7 @@ for (const item in person) { ###### 48. Каким будет результат? ```javascript -console.log(3 + 4 + "5"); +console.log(3 + 4 + '5'); ``` - A: `"345"` @@ -1504,7 +1527,7 @@ const num = parseInt("7*6", 10); ```javascript [1, 2, 3].map(num => { - if (typeof num === "number") return; + if (typeof num === 'number') return; return num * 2; }); ``` @@ -1532,12 +1555,12 @@ const num = parseInt("7*6", 10); ```javascript function getInfo(member, year) { - member.name = "Lydia"; + member.name = 'Lydia'; year = 1998; } -const person = { name: "Sarah" }; -const birthYear = "1997"; +const person = { name: 'Sarah' }; +const birthYear = '1997'; getInfo(person, birthYear); @@ -1569,15 +1592,15 @@ console.log(person, birthYear); ```javascript function greeting() { - throw "Hello world!"; + throw 'Hello world!'; } function sayHi() { try { const data = greeting(); - console.log("It worked!", data); + console.log('It worked!', data); } catch (e) { - console.log("Oh no an error:", e); + console.log('Oh no an error:', e); } } @@ -1596,7 +1619,7 @@ sayHi(); С помощью оператора `throw` мы можем создавать собственные ошибки. С этим оператором вы можете генерировать исключения. Исключением может быть строка, число, логическое значение или объект. В этом случае нашим исключением является строка `'Hello world'`. -С помощью оператора `catch` мы можем указать, что делать, если в блоке` try` выдается исключение. Исключение: строка `'Hello world'`. `e` теперь равно той строке, которую мы записываем. Это приводит к `'Oh error: Hello world'`. +С помощью оператора `catch` мы можем указать, что делать, если в блоке` try` выдается исключение. Исключение: строка `'Hello world'`. `e` теперь равно той строке, которую мы записываем. Это приводит к `'Oh no an error: Hello world'`.

@@ -1607,8 +1630,8 @@ sayHi(); ```javascript function Car() { - this.make = "Lamborghini"; - return { make: "Maserati" }; + this.make = 'Lamborghini'; + return { make: 'Maserati' }; } const myCar = new Car(); @@ -1684,7 +1707,7 @@ Dog.prototype.bark = function() { console.log(`Woof I am ${this.name}`); }; -const pet = new Dog("Mara"); +const pet = new Dog('Mara'); pet.bark(); @@ -1749,7 +1772,7 @@ export default counter; ```javascript // index.js -import myCounter from "./counter"; +import myCounter from './counter'; myCounter += 1; @@ -1778,7 +1801,7 @@ console.log(myCounter); ###### 58. Какой будет вывод? ```javascript -const name = "Lydia"; +const name = 'Lydia'; age = 21; console.log(delete name); @@ -1849,7 +1872,7 @@ console.log(y); ###### 60. Какой будет вывод? ```javascript -const user = { name: "Lydia", age: 21 }; +const user = { name: 'Lydia', age: 21 }; const admin = { admin: true, ...user }; console.log(admin); @@ -1875,9 +1898,9 @@ console.log(admin); ###### 61. Какой будет вывод? ```javascript -const person = { name: "Lydia" }; +const person = { name: 'Lydia' }; -Object.defineProperty(person, "age", { value: 21 }); +Object.defineProperty(person, 'age', { value: 21 }); console.log(person); console.log(Object.keys(person)); @@ -1906,12 +1929,12 @@ console.log(Object.keys(person)); ```javascript const settings = { - username: "lydiahallie", + username: 'lydiahallie', level: 19, health: 90 }; -const data = JSON.stringify(settings, ["level", "health"]); +const data = JSON.stringify(settings, ['level', 'health']); console.log(data); ``` @@ -1961,9 +1984,9 @@ console.log(num2); #### Ответ: A -Унарный оператор `++` _first возвращает_ значение операнда, _then приращивает_ значение операнда. Значение `num1` равно `10`, так как функция увеличений вначале возвращает значение `num`, которое равно `10`, и только затем увеличивает значение `num`. +Унарный оператор `++` _сначала возвращает_ значение операнда, _затем приращивает_ значение операнда. Значение `num1` равно `10`, так как функция увеличений вначале возвращает значение `num`, которое равно `10`, и только затем увеличивает значение `num`. -`num2` - это `10`, так как мы передали `num1` в `incpasePassedNumber`. `number` равно `10` (значение `num1`. Опять же, унарный оператор `++` _first возвращает_ значение операнда, _then увеличивает значение операнда. Значение `number` равно `10`, поэтому `num2` равно `10`. +`num2` - это `10`, так как мы передали `num1` в `incpasePassedNumber`. `number` равно `10` (значение `num1`. Опять же, унарный оператор `++` _сначала возвращает_ значение операнда, _затем увеличивает_ значение операнда. Значение `number` равно `10`, поэтому `num2` равно `10`.

@@ -2035,6 +2058,7 @@ multiply(value); Если вы не возвращаете значение из функции, она возвращает значение `undefined`. При следующем вызове аккумулятор равен `undefined`, а текущее значение равно 3. `undefined` и `3` будут зарегистрированы. При четвертом вызове мы снова не возвращаемся из функции обратного вызова. Аккумулятор снова равен `undefined`, а текущее значение равно `4`. `undefined` и` 4` будут зарегистрированы. +

@@ -2088,6 +2112,7 @@ class Labrador extends Dog { С ключевым словом `super` мы вызываем конструктор родительского класса с заданными аргументами. Конструктор родителя получает аргумент `name`, поэтому нам нужно передать `name` в `super`. Класс `Labrador` получает два аргумента: `name`, поскольку он расширяет `Dog`, и `size` в качестве дополнительного свойства класса `Labrador`. Они оба должны быть переданы в функцию конструктора в `Labrador`, что делается правильно с помощью конструктора 2. +

@@ -2153,7 +2178,7 @@ console.log(Symbol('foo') === Symbol('foo')) ###### 69. Какой будет вывод? ```javascript -const name = "Lydia Hallie" +const name = 'Lydia Hallie' console.log(name.padStart(13)) console.log(name.padStart(2)) ``` @@ -2193,7 +2218,7 @@ console.log("🥑" + "💻"); #### Ответ: A -С помощью оператора `+` вы можете объединять строки. В этом случае мы объединяем строку `""` со строкой `"💻"`, что приводит к `"💻"`. +С помощью оператора `+` вы можете объединять строки. В этом случае мы объединяем строку `"🥑"` со строкой `"💻"`, что приводит к `"🥑💻"`.

@@ -2204,11 +2229,11 @@ console.log("🥑" + "💻"); ```javascript function* startGame() { - const answer = yield "Do you love JavaScript?"; - if (answer !== "Yes") { - return "Oh wow... Guess we're gone here"; + const answer = yield 'Do you love JavaScript?'; + if (answer !== 'Yes') { + return 'Oh wow... Guess we're gone here'; } - return "JavaScript loves you back ❤️"; + return 'JavaScript loves you back ❤️'; } const game = startGame(); @@ -2276,7 +2301,7 @@ console.log(String.raw`Hello\nworld`); ```javascript async function getData() { - return await Promise.resolve("I made it!"); + return await Promise.resolve('I made it!'); } const data = getData(); @@ -2313,7 +2338,7 @@ function addToList(item, list) { return list.push(item); } -const result = addToList("apple", ["banana"]); +const result = addToList('apple', ['banana']); console.log(result); ``` @@ -2373,9 +2398,9 @@ console.log(shape); ###### 76. Какой будет вывод? ```javascript -const { name: myName } = { name: "Lydia" }; +const { firstName: myName } = { firstName: 'Lydia' }; -console.log(name); +console.log(firstName); ``` - A: `"Lydia"` @@ -2388,11 +2413,45 @@ console.log(name); #### Ответ: D -Когда мы распаковываем свойство `name` из правого объекта, мы присваиваем его значение `"Lydia"` переменной с именем `myName`. +Используя [деструктурирующее присваивание](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), мы можем распаковывать значения из массивов или свойства из объектов в отдельные переменные: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// Версия ES5: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Также свойство можно распаковать из объекта и присвоить переменной с именем, отличным от имени свойства объекта: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// Версия ES5: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Тут будет ошибка Uncaught ReferenceError: firstName is not defined +``` + +В этом случае `firstName` не существует как переменная, поэтому попытка доступа к ее значению вызовет `ReferenceError`. + +**Примечание.** Помните о свойствах глобальной области видимости: + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Браузер, например, Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +Всякий раз, когда Javascript не может найти переменную в _текущей области видимости_, то поднимается вверх по [цепочке областей видимости](https://developer.mozilla.org/ru/docs/Web/JavaScript/Closures#лексическая_область_видимости) и ищет ее на каждом уровне, и если достигает области верхнего уровня, также известной как **Глобальная область**, и все еще не находит нужной ссылки, то выдает `ReferenceError`. -С помощью `{name: myName}` мы сообщаем JavaScript, что хотим создать новую переменную с именем `myName` со значением свойства `name` в правой части. +- В **браузерах**, таких как _Chrome_, `name` является _устаревшим свойством глобальной области_. В этом примере код выполняется внутри _глобальной области_ и нет определяемой пользователем локальной переменной `name`, поэтому интерпретатор ищет предопределенные _переменные/свойства_ в глобальной области видимости, что в случае браузеров происходит через объект `window` и возвращается значение [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name), которое равно **пустой строке**. -Поскольку мы пытаемся зарегистрировать `name`, переменную, которая не определена, выдается ReferenceError. +- В **NodeJS** такого свойства в "глобальном" объекте нет, поэтому попытка доступа к несуществующей переменной вызовет [ReferenceError](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Errors/Not_defined).

@@ -2474,7 +2533,7 @@ console.log(addFunction(5 * 2)); ###### 79. Какой будет вывод? ```javascript -const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫'] for (let item in myLifeSummedUp) { console.log(item) @@ -2544,9 +2603,9 @@ function sayHi(name) { console.log(sayHi()) ``` -- A: `Hello there, ` -- B: `Hello there, undefined` -- C: `Hello there, null` +- A: `Hi there, ` +- B: `Hi there, undefined` +- C: `Hi there, null` - D: `ReferenceError`
Ответ @@ -2570,13 +2629,13 @@ console.log(sayHi()) ###### 82. Какой будет вывод? ```javascript -var status = "😎" +var status = '😎' setTimeout(() => { - const status = "😍" + const status = '😍' const data = { - status: "🥑", + status: '🥑', getStatus() { return this.status } @@ -2601,7 +2660,6 @@ setTimeout(() => { С помощью метода `call` мы можем изменить объект, на который ссылается ключевое слово `this`. В **функциях** ключевое слово `this` относится к _объекту, которому принадлежит функция_. Мы объявили функцию `setTimeout` для объекта _global_, поэтому в функции `setTimeout` ключевое слово `this` ссылается на объект _global_. В глобальном объекте есть переменная с именем _status_ со значением `"😎"`. При регистрации `this.status` выводится `"😎"`. -

@@ -2611,12 +2669,12 @@ setTimeout(() => { ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } let city = person.city -city = "Amsterdam" +city = 'Amsterdam' console.log(person) ``` @@ -2736,7 +2794,7 @@ function getName(name) { ###### 87. Какой будет вывод? ```javascript -console.log("I want pizza"[0]) +console.log('I want pizza'[0]) ``` - A: `"""` @@ -2791,11 +2849,11 @@ sum(10) ```javascript // module.js -export default () => "Hello world" -export const name = "Lydia" +export default () => 'Hello world' +export const name = 'Lydia' // index.js -import * as data from "./module" +import * as data from './module' console.log(data) ``` @@ -2828,7 +2886,7 @@ class Person { } } -const member = new Person("John") +const member = new Person('John') console.log(typeof member) ``` @@ -2850,7 +2908,7 @@ function Person() { } ``` -Вызов конструктора функции с `new` приводит к созданию экземпляра `Person`, ключевое слово `typeof` возвращает `"object"` для экземпляра. `typeof member` возвращает `"объект"`. +Вызов конструктора функции с `new` приводит к созданию экземпляра `Person`, ключевое слово `typeof` возвращает `"object"` для экземпляра. `typeof member` возвращает `"object"`.

@@ -2888,10 +2946,11 @@ console.log(newList.push(5)) ```javascript function giveLydiaPizza() { - return "Here is pizza!" + return 'Here is pizza!' } -const giveLydiaChocolate = () => "Here's chocolate... now go hit the gym already." +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already." console.log(giveLydiaPizza.prototype) console.log(giveLydiaChocolate.prototype) @@ -2918,7 +2977,7 @@ console.log(giveLydiaChocolate.prototype) ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } @@ -2982,6 +3041,7 @@ getItems(["banana", "apple"], "pear", "orange") ``` Приведенный выше пример работает. Это возвращает массив `[ 'banana', 'apple', 'orange', 'pear' ]` +

@@ -2991,13 +3051,10 @@ getItems(["banana", "apple"], "pear", "orange") ```javascript function nums(a, b) { - if - (a > b) - console.log('a is bigger') - else - console.log('b is bigger') + if (a > b) console.log('a is bigger') + else console.log('b is bigger') return - a + b + a + b; } console.log(nums(4, 2)) @@ -3035,13 +3092,13 @@ console.log(nums(1, 2)) ```javascript class Person { constructor() { - this.name = "Lydia" + this.name = 'Lydia' } } Person = class AnotherPerson { constructor() { - this.name = "Sarah" + this.name = 'Sarah' } } @@ -3121,15 +3178,15 @@ console.log(getUser(user)) Функция `getList` получает массив в качестве аргумента. Между скобками функции `getList` мы сразу же деструктурируем этот массив. Вы можете увидеть это как: - `[x, ...y] = [1, 2, 3, 4]` +`[x, ...y] = [1, 2, 3, 4]` С помощью оставшихся параметров `... y` мы помещаем все "оставшиеся" аргументы в массив. Остальные аргументы - это `2`, `3` и `4` в этом случае. Значение `y` является массивом, содержащим все остальные параметры. В этом случае значение `x` равно `1`, поэтому, мы видим в логе `[x, y]`, `[1, [2, 3, 4]]`. -Функция `getUser` получает объект. В случае функций со стрелками мы не можем писать фигурные скобки, если мы просто возвращаем одно значение. Однако, если вы хотите вернуть _объект_ из стрелочной функции, вы должны написать его в скобках, в противном случае никакое значение не возвращается! Следующая функция вернула бы объект: +Функция `getUser` получает объект. В стрелочных функциях нам _не нужно_ писать фигурные скобки, если мы просто возвращаем одно значение. Однако, если вы хотите мгновенно вернуть _object_ из стрелочной функции, вы должны написать его между круглыми скобками, иначе все, что находится между двумя фигурными скобками, будет интерпретироваться как оператор блока. В этом случае код между фигурными скобками не является допустимым кодом JavaScript, поэтому выдается `SyntaxError`. -```const getUser = user => ({ name: user.name, age: user.age })``` +Следующая функция вернула бы объект: -Поскольку в этом случае значение не возвращается, функция возвращает значение `undefined`. +```const getUser = user => ({ name: user.name, age: user.age })```

@@ -3139,7 +3196,7 @@ console.log(getUser(user)) ###### 99. Какой будет вывод? ```javascript -const name = "Lydia" +const name = 'Lydia' console.log(name()) ``` @@ -3198,7 +3255,7 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol` ```javascript const one = (false || {} || null) -const two = (null || false || "") +const two = (null || false || '') const three = ([] || 0 || true) console.log(one, two, three) @@ -3218,9 +3275,9 @@ console.log(one, two, three) `(false || {} || null)`: пустой объект `{}` является истинным значением. Это первое (и единственное) истинное значение, которое возвращается. `one` содержит `{}`. -`(null || false ||" ")`: все операнды являются ложными значениями. Это означает, что прошедший операнд `""` возвращается. `two` содержит `""`. +`(null || false || "")`: все операнды являются ложными значениями. Это означает, что прошедший операнд `""` возвращается. `two` содержит `""`. -`([] || 0 ||" ")`: пустой массив `[]` является истинным значением. Это первое истинное значение, которое возвращается. `three` присвоено `[]`. +`([] || 0 || "")`: пустой массив `[]` является истинным значением. Это первое истинное значение, которое возвращается. `three` присвоено `[]`.

@@ -3256,7 +3313,7 @@ secondFunction() #### Ответ: D -С обещанием мы в основном говорим: "Я хочу выполнить эту функцию и откладываю ее, пока она выполняется, поскольку это может занять некоторое время". Только когда определенное значение разрешено (или отклонено), и когда стек вызовов пуст, я хочу использовать это значение. +С обещанием мы в основном говорим: _"Я хочу выполнить эту функцию и откладываю ее, пока она выполняется, поскольку это может занять некоторое время. Только когда определенное значение разрешено (или отклонено), и когда стек вызовов пуст, я хочу использовать это значение_". Мы можем получить это значение с помощью ключевого слова `.then` и `await` в функции `async`. Хотя мы можем получить значение обещания с помощью `.then` и `await`, они работают немного по-разному. @@ -3277,8 +3334,8 @@ secondFunction() const set = new Set() set.add(1) -set.add("Lydia") -set.add({ name: "Lydia" }) +set.add('Lydia') +set.add({ name: 'Lydia' }) for (let item of set) { console.log(item + 2) @@ -3316,7 +3373,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Ответ @@ -3324,7 +3381,7 @@ Promise.resolve(5) #### Ответ: C -Мы можем передать любой тип значения, которое мы хотим, в `Promise.resolve`, либо обещание, либо не обещание. Сам метод возвращает обещание с разрешенным значением. Если вы передадите обычную функцию, это будет разрешенное обещание с обычным значением. Если вы передадите обещание, это будет разрешенное обещание с разрешенным значением этого пройденного обещания. +Мы можем передать любой тип значения, которое мы хотим, в `Promise.resolve`, либо обещание, либо не обещание. Сам метод возвращает обещание с разрешенным значением (``). Если вы передадите обычную функцию, это будет разрешенное обещание с обычным значением. Если вы передадите обещание, это будет разрешенное обещание с разрешенным значением этого пройденного обещания. В этом случае мы просто передали числовое значение `5`. Возвращается разрешенное обещание со значением `5`. @@ -3338,13 +3395,13 @@ Promise.resolve(5) ```javascript function compareMembers(person1, person2 = person) { if (person1 !== person2) { - console.log("Not the same!") + console.log('Not the same!') } else { - console.log("They are the same!") + console.log('They are the same!') } } -const person = { name: "Lydia" } +const person = { name: 'Lydia' } compareMembers(person) ``` @@ -3383,7 +3440,7 @@ const colorConfig = { yellow: false, } -const colors = ["pink", "red", "blue"] +const colors = ['pink', 'red', 'blue'] console.log(colorConfig.colors[1]) ``` @@ -3400,7 +3457,7 @@ console.log(colorConfig.colors[1]) В JavaScript у нас есть два способа доступа к свойствам объекта: нотация в скобках или нотация в точках. В этом примере мы используем точечную нотацию (`colorConfig.colors`) вместо скобочной нотации (`colorConfig["colors"]`). -В точечной нотации JavaScript пытается найти свойство объекта с таким точным именем. В этом примере JavaScript пытается найти свойство с именем `colors` в объекте `colorConfig`. Не существует свойства с именем `colorConfig`, поэтому возвращается `undefined`. Затем мы пытаемся получить доступ к значению первого элемента, используя `[1]`. Мы не можем сделать это для значения, которое `undefined`, поэтому оно выдает `TypeError`: `Cannot read свойство '1' of undefined`. +В точечной нотации JavaScript пытается найти свойство объекта с таким точным именем. В этом примере JavaScript пытается найти свойство с именем `colors` в объекте `colorConfig`. Не существует свойства с именем `colors`, поэтому возвращается `undefined`. Затем мы пытаемся получить доступ к значению первого элемента, используя `[1]`. Мы не можем сделать это для значения, которое `undefined`, поэтому оно выдает `TypeError`: `Cannot read свойство '1' of undefined`. JavaScript интерпретирует (или распаковывает) операторы. Когда мы используем скобочные обозначения, он видит первую открывающую скобку `[` и продолжает работать, пока не найдет закрывающую скобку `]`. Только тогда он оценит утверждение. Если бы мы использовали `colorConfig[colors [1]]`, он бы возвратил значение свойства `red` объекта `colorConfig`. @@ -3462,7 +3519,7 @@ emojis.splice(1, 2, '✨') --- -###### 109. Какое значение будет на выходе? +###### 109. Какое значение будет на выходе? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3522,7 +3579,7 @@ const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] // Преобразование объекта в допустимый JSON, затем преобразование строки JSON в значение JavaScript: -const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' +const jsonArray = JSON.stringify({ name: 'Lydia' }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3554,11 +3611,11 @@ getName() #### Ответ: D -Каждая функция имеет свой собственный _контекст исполнения_ (или _область действия_). Функция `getName` сначала ищет в своем собственном контексте (области действия), чтобы увидеть, содержит ли она переменную `name`, к которой мы пытаемся получить доступ. В этом случае функция `getName` содержит собственную переменную `name`: мы объявляем переменную `name` с ключевым словом `let` и значением `'Sarah'`. +Каждая функция имеет свой собственный _контекст исполнения_ (или _область видимости_). Функция `getName` сначала ищет в своем собственном контексте (области видимости), чтобы увидеть, содержит ли она переменную `name`, к которой мы пытаемся получить доступ. В этом случае функция `getName` содержит собственную переменную `name`: мы объявляем переменную `name` с ключевым словом `let` и значением `'Sarah'`. Переменные с ключевым словом `let` (и `const`) поднимаются в начало функции, в отличие от `var`, которые не инициализируется. Они недоступны до того, как мы объявим (инициализируем) их строку. Это называется "временной мертвой зоной". Когда мы пытаемся получить доступ к переменным до их объявления, JavaScript выдает `ReferenceError`. -Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал "Лидию". +Если бы мы не объявили переменную `name` в функции `getName`, движок javascript посмотрел бы вниз по _цепочки области действия_. Внешняя область имеет переменную с именем `name` со значением `Lydia`. В этом случае он бы записал `Lydia`. ```javascript let name = 'Lydia' @@ -3605,7 +3662,7 @@ console.log(two.next().value) Используя ключевое слово `yield`, мы получаем значения в функции генератора. С помощью ключевого слова `yield*` мы можем получить значения из другой функции-генератора или итерируемого объекта (например, массива). -В `generatorOne` мы получаем весь массив `[' a ',' b ',' c ']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. +В `generatorOne` мы получаем весь массив `['a', 'b', 'c']`, используя ключевое слово `yield`. Значение свойства `value` для объекта, возвращаемого методом `next` для `one` (`one.next().value`), равно всему массиву `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] @@ -3671,7 +3728,11 @@ config = null #### Ответ: C -Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают метку _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова в `setInterval` является стрелочной функцией стрелки (таким образом, привязанной к объекту `config`), функция обратного вызова все еще содержит ссылку на объект `config`. Пока есть ссылка, объект не будет собран в мусор. Поскольку сборщик мусора не отрабатывает, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000 мс (1с). +Обычно, когда мы устанавливаем объекты равными `null`, эти объекты получают статус _собрано в мусор_, так как больше нет ссылок на этот объект. Однако, поскольку функция обратного вызова внутри `setInterval` является стрелочной функцией (таким образом, привязанной к объекту `config`), функция обратного вызова по-прежнему содержит ссылку на объект `config`. +Пока есть ссылка, объект не будет собирать мусор. +Так как это интервал, установка `config` в `null` или `delete`-ing `config.alert` не приведет к сбору мусора для интервала, поэтому интервал все равно будет вызываться. +Его следует очистить с помощью `clearInterval(config.alert)`, чтобы удалить его из памяти. +Поскольку он не был очищен, функция обратного вызова `setInterval` будет по-прежнему вызываться каждые 1000мс (1с).

@@ -3718,14 +3779,14 @@ myMap.get(() => 'greeting') ```javascript const person = { - name: "Lydia", + name: 'Lydia', age: 21 } const changeAge = (x = { ...person }) => x.age += 1 const changeAgeAndName = (x = { ...person }) => { x.age += 1 - x.name = "Sarah" + x.name = 'Sarah' } changeAge(person) @@ -3752,3 +3813,1334 @@ console.log(person)

+ +--- + +###### 117. Какой из следующих наборов параметров вернет `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Ответ +

+ +#### Ответ: C + +С помощью оператора распространения (spread) `...` мы можем _распределить_ итерации в отдельньные элементы. `sumValues` принимает три аргумента:`x`, `y` и `z`. `...[1, 2, 3]` приведет к перечню `1, 2, 3`, который мы передаем функции `sumValues`. + +

+
+ +--- + +###### 118. Что будет на выходе? + +```javascript +let num = 1; +const list = ["🥳", "🤠", "🥰", "🤪"]; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +С операндом `+=` мы увеличиваем значение `num` на `1`. `num` имеет начальное значение `1`, поэтому `1 + 1` равно `2`. Элементом второго индекса в массиве `list` и является вывод `console.log (list [2])`🥰. + +

+
+ +--- + +###### 119. Что будет на выходе? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound' + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + } +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +С необязательным оператором связывания `?.` нам больше не нужно явно проверять, действительны ли более глубокие вложенные значения или нет. Если мы пытаемся получить доступ к свойству со (_нулевым_) значением `undefined` или `null`, выражение замыкается и возвращает `undefined`. + +`person.pet?.name`: `person` имеет свойство с именем `pet`: `person.pet` не нулевое. Оно имеет свойство с именем `name`, и возвращает `Mara`. +`person.pet?.family?.name`: `person` имеет свойство с именем `pet`: `person.pet` не нулевое. `pet` _не_ имеет свойство с именем `family`, `person.pet.family` нулевое. Выражение возвращает `undefined`. +`person.getFullName?.()`: `person` имеет свойство с именем `getFullName`: `person.getFullName()` не нулевое, и может быть вызвано, возвращает `Lydia Hallie`. +`member.getLastName?.()`: `member` не определено: `member.getLastName()` нулевое. Выражение возвращает `undefined`. + +

+
+ +--- + +###### 120. Что будет на выходе? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Ответ +

+ +#### Ответ: B + +Мы передали условие `groceries.indexOf("banana")` в оператор `if`. `groceries.indexOf("banana")` возвращает `0`, что является ложным значением. Поскольку условие в операторе `if` ложно, выполняется код в блоке `else`, и в лог выводится ``We don't have to buy bananas!``. + +

+
+ +--- + +###### 121. Что будет на выходе? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + } +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Ответ +

+ +#### Ответ: D + +Метод `language` является `сеттером`. Сеттеры не содержат действительного значения, их целью является изменение свойств. При вызове метода `setter` возвращается `undefined`. + +

+
+ +--- + +###### 122. Что будет на выходе? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Ответ +

+ +#### Ответ: C + +`typeof name` возвращает `"строку"`. Строка `"string"` является истинным значением, поэтому `!typeof name` возвращает логическое значение `false`. `false === "object"` и `false === "string"` оба возвращают `false`. + +(Если бы мы хотели проверить, был ли тип (не)равен определенному типу, мы должны были написать `!==` вместо `!typeof`) + +

+
+ +--- + +###### 123. Что будет на выходе? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Ответ +

+ +#### Ответ: A + +Функция `add` возвращает стрелочную функцию, которая возвращает стрелочную функцию, которая возвращает стрелочную функцию (все еще тут?). Первая функция получает аргумент `x` со значением `4`. Мы вызываем вторую функцию, которая получает аргумент `y` со значением `5`. Затем мы вызываем третью функцию, которая получает аргумент `z` со значением `6`. Когда мы пытаемся получить доступ к значениям `x`, `y` и `z` в функции последней стрелки, движок JS поднимается вверх по цепочке областей видимости, чтобы найти значения для `x` и `y` соответственно. Это возвращает `4` `5` `6`. + +

+
+ +--- + +###### 124. Что будет на выходе? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Ответ +

+ +#### Ответ: C + +Функция генератора `range` возвращает асинхронный объект с обещаниями для каждого элемента в диапазоне, который мы передаем: `Promise {1}`, `Promise {2}`, `Promise {3}`. Мы устанавливаем переменную `gen` равной асинхронному объекту, после чего зацикливаем ее, используя цикл `for await ... of`. Мы устанавливаем переменную `item` равной возвращаемым значениям `Promise`: сначала `Promise {1}`, затем `Promise {2}`, затем `Promise {3}`. Так как мы _ожидаем_ значение `item`, разрешается обещание, возвращаются разрешенные _значения_ обещания: `1`, `2`, затем `3`. + +

+
+ +--- + +###### 125. Что будет на выходе? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Ответ +

+ +#### Ответ: D + +`myFunc` ожидает объект со свойствами `x`, `y` и `z` в качестве аргумента. Поскольку мы передаем только три отдельных числовых значения (1, 2, 3) вместо одного объекта со свойствами `x`, `y` и `z` ({x: 1, y: 2, z: 3}), то `x`, `y` и `z` имеют значение по умолчанию` undefined`. + +

+
+ +--- + +###### 126. Что будет на выходе? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat({ + 'en-US', + { style: 'unit', unit: 'mile-per-hour' } + }).format(speed) + + const formattedAmount = new Intl.NumberFormat({ + 'en-US', + { style: 'currency', currency: 'USD' } + }).format(amount) + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
Ответ +

+ +#### Ответ: B + +С помощью метода `Intl.NumberFormat` мы можем форматировать числовые значения в любой локали. Мы форматируем числовое значение `130` для локали `en-US` как `unit` в `mile-per-hour`, что приводит к `130 mph`. Числовое значение `300` для локали `en-US` в качестве `currentcy` в `USD` приводит к `$300.00`. + +

+
+ +--- + +###### 127. Что будет на выходе? + +```javascript +const spookyItems = ["👻", "🎃", "🕸"]; +({ item: spookyItems[3] } = { item: "💀" }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Ответ +

+ +#### Ответ: B + +Деструктурируя объекты, мы можем распаковать значения из правого объекта и присвоить распакованному значению значение того же по имени свойства в левом объекте. В этом случае мы присваиваем значение "💀" `spookyItems[3]`. Это означает, что мы модифицируем массив `spookyItems`, добавляем к нему «💀». При логировании `spookyItems` выводится ` ["👻", "🎃", "🕸", "💀"]`. + +

+
+ +--- + +###### 128. Что будет на выходе? + +```javascript +const name = "Lydia Hallie"; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Ответ +

+ +#### Ответ: C + +С помощью метода `Number.isNaN` вы можете проверить, является ли передаваемое вами значение _числовым значением_ и равно ли оно `NaN`. `name` не является числовым значением, поэтому `Number.isNaN(name)` возвращает `false`. `age` является числовым значением, но не равно `NaN`, поэтому `Number.isNaN(age)` возвращает `false`. + +С помощью метода `isNaN` вы можете проверить, не является ли передаваемое вами значение числом. `name` не является числом, поэтому `isNaN(name)` возвращает true. `age` - это число, поэтому `isNaN(age)` возвращает `false`. + +

+
+ +--- + +###### 129. Что будет на выходе? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: D + +Переменные, объявленные с ключевым словом `const`, не имеют ссылки до их инициализации: это называется _временная мертвая зона_. В функции `getInfo` переменная `randomValue` находится в области видимости `getInfo`. В строке, где мы хотим записать значение `typeof randomValue`, переменная `randomValue` еще не инициализирована: выдается `ReferenceError`! Движок не пошел по цепочке областей видимости, так как мы объявили переменную `randomValue` в функции `getInfo`. + +

+
+ +--- + +###### 130. Что будет на выходе? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Ответ +

+ +#### Ответ: C + +В блоке `try` мы выводим в лог ожидаемое значение переменной `myPromise`: `"Woah some cool data"`. Поскольку в блоке `try` не было выдано никаких ошибок, код в блоке `catch` не запускается. Код в блоке `finally` _всегда_ выполняется, `"Oh finally!"` также выводится в лог. + +

+
+ +--- + +###### 131. Что будет на выходе? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Ответ +

+ +#### Ответ: B + +С помощью метода `flat` мы можем создать новый плоский массив. Глубина уплощенного массива зависит от значения, которое мы передаем. В этом случае мы передали значение `1` (которое нам не нужно, это значение по умолчанию), что означает, что будут объединены только массивы на первой глубине. `['🥑']` и `['✨', '✨', ['🍕', '🍕']]` в этом случае. Конкатенация этих двух массивов приводит к `['🥑', '✨', '✨', ['🍕', '🍕']]`. + +

+
+ +--- + +###### 132. Что будет на выходе? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Ответ +

+ +#### Ответ: D + +`counterOne` экземпляр класса `Counter`. Counter класс содержит метод `increment` и свойство `count` в конструкторе. Сперва, при помощи `counterOne.increment()`, мы дважды вызываем метод `increment`. `counterOne.count` становится `2`. + + + +Затем, мы создаем новую переменную `counterTwo`, и присваиваем ей `counterOne`. Поскольку объекты передаются по ссылке, мы просто создаем новую ссылку на то же место в памяти, на которое указывает `counterOne`. Поскольку переменные ссылаются на то же место в памяти, любые изменения, внесенные в объект, на который ссылается `counterTwo`, также применяются к` counterOne`. Теперь `counterTwo.count` равно `2`. + +Мы вызываем `counterTwo.increment()`, что устанавливает значение `count` равное `3`. Затем мы выводим в консоль значение переменной `counterOne`, которое равно `3`. + + + +

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

+ +#### Ответ: D + +Сначала мы вызываем `funcOne`. В первой строке `funcOne` мы вызываем _асинхронную_ функцию `setTimeout`, из которой обратный вызов отправляется в веб-API. (см. мою статью о цикле событий здесь.) + +Затем мы вызываем обещание `myPromise`, которое является _асинхронной_ операцией. + +И обещание, и тайм-аут являются асинхронными операциями, функция продолжает работать, пока она занята выполнением обещания и обработкой обратного вызова `setTimeout`. Это означает, что `Last line 1!` регистрируется первой, так как это не асинхронная операция. + +Поскольку стек вызовов еще не пуст, функция `setTimeout` и обещание в `funcOne` еще не могут быть добавлены в стек вызовов. + +В `funcTwo` переменная `res` получает `Promise`, потому что `Promise.resolve(Promise.resolve('Promise'))` эквивалентно `Promise.resolve('Promise')`, так как разрешение обещания просто разрешает его стоимость. `await` в этой строке останавливает выполнение функции до тех пор, пока она не получит разрешение промиса, а затем продолжает работать синхронно до завершения, поэтому `Promise 2!`, а затем `Last line 2!` регистрируются, а `setTimeout` отправляется в Web API. + +Тогда стек вызовов пуст. Промисы — это _микрозадачи_, поэтому они решаются первыми, когда стек вызовов пуст, поэтому `Promise 1!` регистрируется. + +Теперь, поскольку `funcTwo` выталкивается из стека вызовов, стек вызовов пуст. Обратные вызовы, ожидающие в очереди (`() => console.log("Timeout 1!")` из `funcOne`, и `() => console.log("Timeout 2!")` из `funcTwo`) добавляются в стек вызовов один за другим. Первый обратный вызов регистрирует `Timeout 1!` и удаляется из стека. Затем второй обратный вызов регистрирует `Timeout 2!` и удаляется из стека. + +

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

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

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

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

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

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

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

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

+
+ +--- + +###### 138. Что будет на выходе? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Ответ +

+ +#### Ответ: A + +Во-первых, мы вызваем `myFunc()` без передачи каких-либо аргументов. Поскольку мы не передаем аргументы, `num` и `value` получают свои значения по умолчанию: `num` равно `2`, а `value` возвращаемое значение функции `add`. В функцию `add` мы передаем в качестве аргумента `num` со значением `2`. `add` возвращает `4`, что является значением `value`. + +Затем мы вызваем `myFunc(3)` и передаем значение `3` в качестве значения аргумента `num`. Мы не передаем аргумент для `value`. Поскольку мы не передаем значение для аргумента `value`, он получаеи значение по умолчанию: возвращаемое значение функции `add`. В `add` мы передаем `num`, значение которого равно `3`. `add` возвращает `6`, что является значением `value`. + +

+
+ +--- + +###### 139. Что будет на выходе? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Ответ +

+ +#### Ответ: D + +В ES2020 мы можем добавлять приватные переменные в классы с помощью символа `#`. Мы не можем получить доступ к этим переменным вне класса. Когда мы пытаемся записать `counter.#number`, выдается `SyntaxError`: мы не можем получить доступ вне класса `Counter`! + +

+
+ +--- + +###### 140. В каком случае не будет ошибки? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Ответ +

+ +#### Ответ: B + +Чтобы выполнить итерацию по `members` в каждом элементе массива `teams`, нам нужно передать `teams[i].members` в функцию генератора `getMembers`. Функция генератора возвращает объект генератора. Чтобы перебрать каждый элемент в этом объекте-генераторе, нам нужно использовать `yield*`. + +Если бы мы написали `yield`, `return yield` или `return`, вся функция генератора была бы возвращена при первом вызове метода `next`. + +

+
+ +--- + +###### 141. Что будет на выходе? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Ответ +

+ +#### Ответ: C + +Функция `addHobby` получает два аргумента, `hobby` и `hobbies`, со значением по умолчанию массива `hobbies` в объекте `person`. + +Во-первых, мы вызываем функцию `addHobby` и передаем `"running"` в качестве значения для `hobby`, а пустой массив в качестве значения для `hobbies`. Так как мы передаем пустой массив в качестве значения для `hobbies`, `"running"` добавляется к этому пустому массиву. + +Затем мы вызываем функцию `addHobby` и передаем `dancing` в качестве значения для `hobby`. Мы не передавали значение для `hobbies`, поэтому оно получает значение по умолчанию, свойство `hobbies` объекта `person`. Мы помещаем хобби `dancing` в массив `person.hobbies`. + +Наконец, мы вызываем функцию `addHobby` и передаем `"baking"` в качестве значения для `hobby`, а массив `person.hobbies` в качестве значения для `hobbies`. Мы помещаем хобби `baking` в массив `person.hobbies`. + +После нажатия `танцы` и `выпечка`, значение `person.hobbies` равно `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Что будет на выходе? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Nothing, we didn't call any method + +
Ответ +

+ +#### Ответ: B + +Мы создаем переменную `pet`, которая является экземпляром класса `Flamingo`. Когда мы создаем этот экземпляр, вызывается `constructor` для `Flamingo`. Сначала регистрируется `"I'm pink. 🌸"`, после чего мы вызываем `super()`. `super()` вызывает конструктор родительского класса `Bird`. Конструктор в `Bird` вызывается и регистрирует `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Какой/какие из вариантов приведет к ошибке? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 и 2 +- C: 3 и 4 +- D: 3 + +
Ответ +

+ +#### Ответ: D + +Ключевое слово `const` просто означает, что мы не можем _повторно объявить_ значение этой переменной, оно доступно только для чтения. Однако само значение не является неизменным. Свойства массива `emojis` можно изменить, например, добавив новые значения, объединив их или установив длину массива на 0. + +

+
+ +--- + +###### 144. Что нам нужно добавить к объекту `person`, чтобы получить `["Lydia Hallie", 21]` в качестве вывода `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Ничего, объекты итерируется по умолчанию +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Ответ +

+ +#### Ответ: C + +По умолчанию объекты не являются итерируемыми. Итерируемым объект становится, если присутствует протокол итератора. Мы можем добавить это вручную, добавив символ итератора `[Symbol.iterator]`, который должен возвращать объект-генератор, например, сделав его функцией-генератором `*[Symbol.iterator]() {}`. Эта функция-генератор должна возвращать `Object.values` объекта `person`, если мы хотим, чтобы он возвращал массив `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Что будет на выходе? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Ответ +

+ +#### Ответ: C + +Условие `if` внутри цикла `forEach` проверяет, является ли значение `num` истинным или ложным. Поскольку первое число в массиве `nums` равно `0`, то есть ложное значение, блок оператора `if` не будет выполнен. `count` увеличивается только для остальных 3 чисел в массиве `nums`: `1`, `2` и `3`. Поскольку `count` увеличивается на 1 3 раза, значение `count` равно `3`. + +

+
+ +--- + +###### 146. Что будет на выходе? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Ответ +

+ +#### Ответ: D + +`?` позволяет нам дополнительно получить доступ к более глубоким вложенным свойствам внутри объектов. Мы пытаемся зарегистрировать элемент с индексом `1` в подмассиве с индексом `1` массива `fruits`. Если подмассив с индексом `1` в массиве `fruits` не существует, он просто вернет `undefined`. Если подмассив с индексом `1` в массиве `fruits` существует, но в этом подмассиве нет элемента с индексом `1`, он также вернет значение `undefined`. + +Во-первых, мы пытаемся зарегистрировать второй элемент в `['🍍']` подмассива `[['🍊', '🍌'], ['🍍']]`. Этот подмассив содержит только один элемент, что означает, что в индексе `1` нет элемента, и возвращает значение `undefined`. + +Затем мы вызываем функцию `getFruits` без передачи значения в качестве аргумента, что означает, что `fruits` по умолчанию имеет значение `undefined`. Поскольку мы условно связываем элемент с индексом `1` массива `fruits`, он возвращает значение `undefined`, поскольку этот элемент с индексом `1` не существует. + +Наконец, мы попытаемся зарегистрировать второй элемент в `['🍊', '🍌']` подмассива `['🍍'], ['🍊', '🍌']`. Элемент с индексом `1` в этом подмассиве — `🍌`, который регистрируется. + +

+
+ +--- + +###### 147. Что будет на выходе? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +Мы устанавливаем переменную `calc` равной новому экземпляру класса `Calc`. Затем мы создаем экземпляр нового экземпляра `Calc` и вызываем метод увеличения для этого экземпляра. Поскольку свойство `count` находится в конструкторе класса `Calc`, свойство `count` не используется в прототипе `Calc`. Это означает, что значение `count` не было обновлено для экземпляра, на который указывает `calc`, `count` по-прежнему равен `0`. + +

+
+ +--- + +###### 148. Что будет на выходе? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +Функция `updateUser` обновляет значения свойств `email` и `password` у пользователя, если их значения переданы в функцию, после чего функция возвращает объект `user`. Возвращаемое значение функции `updateUser` — это объект `user`, что означает, что значение `updatedUser` является ссылкой на тот же объект `user`, на который указывает `user`. `updatedUser === user` равно `true`. + +

+
+ +--- + +###### 149. Что будет на выходе? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Ответ +

+ +#### Ответ: C + +Во-первых, мы вызываем метод `slice` для массива фруктов. Метод `slice` не изменяет исходный массив, а возвращает значение, которое было вырезано из массива: банановый смайлик. +Затем мы вызываем метод `splice` для массива фруктов. Метод `splice` изменяет исходный массив, что означает, что массив фруктов теперь состоит из `['🍊', '🍎']`. +Наконец, мы вызываем метод `unshift` для массива `fruit`, который изменяет исходный массив, добавляя предоставленное значение, в данном случае `🍇`, в качестве первого элемента в массиве. Массив фруктов теперь состоит из `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Что будет на выходе? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: B + +Ключи объекта преобразуются в строки. + +Поскольку значение `dog` является объектом, `animals[dog]` на самом деле означает, что мы создаем новое свойство под названием `"object Object"`, равное новому объекту. `animals["object Object"]` теперь равно `{ emoji: "🐶", name: "Mara"}`. + +`cat` также является объектом, что означает, что `animals[cat]` на самом деле означает, что мы перезаписываем значение `animals["object Object"]` новыми свойствами кота. + +Регистрация `animals[dog]`, или фактически `animals["object Object"]`, поскольку преобразование объекта `dog` в строку приводит к `"object Object"`, возвращает `{ emoji: "🐈", name: " Сара"}`. + +

+
+ +--- + +###### 151. Что будет на выходе? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Ответ +

+ +#### Ответ: A + +Функция `updateEmail` представляет собой стрелочную функцию и не привязана к объекту пользователя. Это означает, что ключевое слово `this` не относится к объекту `user`, а в данном случае относится к глобальной области видимости. Значение `email` в объекте `user` не обновляется. При регистрации значения `user.email` возвращается исходное значение `my@email.com`. + +

+
+ +--- + +###### 152. Что будет на выходе? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Ответ +

+ +#### Ответ: D + +Метод `Promise.all` выполняет переданные промисы параллельно. Если одно обещание не выполняется, метод `Promise.all` _отколняется_ со значением отклоненного обещания. В этом случае `promise3` отклонен со значением `"Third"`. Мы перехватываем отклоненное значение в цепочке методов `catch` при вызове `runPromises`, чтобы перехватывать любые ошибки внутри функции `runPromises`. Только `"Third"` регистрируется, так как `promise3` отклонено с этим значением. + +

+
+ +--- + +###### 153. Каким должно быть значение `method` для регистрации `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Ответ +

+ +#### Ответ: C + +Метод `fromEntries` превращает двумерный массив в объект. Первый элемент в каждом подмассиве будет ключом, а второй элемент в каждом подмассиве будет значением. В этом случае мы сопоставляем массив `keys`, который возвращает массив, первый элемент которого является элементом массива ключей текущего индекса, а второй элемент является элементом массива значений текущего индекса. + +Это создает массив подмассивов, содержащих правильные ключи и значения, что приводит к `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Что будет на выходе? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Ответ +

+ +#### Ответ: C + +Значением по умолчанию для `address` является пустой объект `{}`. Когда мы устанавливаем переменную `member` равной объекту, возвращаемому функцией `createMember`, мы не передаем значение для адреса, что означает, что значение адреса является пустым объектом по умолчанию `{}`. Пустой объект является истинным значением, что означает, что условие `address ? address : null` условно возвращает `true`. Значением адреса является пустой объект `{}`. + +

+
+ +--- + +###### 155. Что будет на выходе? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Ответ +

+ +#### Ответ: B + +Условие в операторе `if` проверяет, равно ли значение `!typeof randomValue` "строке". Оператор `!` преобразует значение в логическое значение. Если значение истинно, возвращаемое значение будет "ложным", если значение ложным, возвращаемое значение будет "истинным". В этом случае возвращаемое значение `typeof randomValue` является истинным значением `"number"`, что означает, что значение `!typeof randomValue` является логическим значением `false`. + +`!typeof randomValue === "string"` всегда возвращает `false`, поскольку на самом деле мы проверяем `false === "string"`. Поскольку условие вернуло `false`, запускается блок кода оператора `else`, и в журнал заносится сообщение `Yay it's a string!`. + +

+
diff --git a/sq-KS/README_sq_KS.md b/sq-KS/README_sq_KS.md new file mode 100644 index 00000000..2392abb4 --- /dev/null +++ b/sq-KS/README_sq_KS.md @@ -0,0 +1,5145 @@ +
+ +

Pyetje Javascript

+ +--- + +Pyetjet të cilat mund të kenë më shumë se një përgjigje të saktë postohen në **storie** në këtë [Instagram](https://www.instagram.com/theavocoder), të cilat do të postohen edhe këtu! Përditësimi i fundit: 12 Qershor + +Nga konceptet bazike tek ato të avancuara: testo se sa mirë e njeh JavaScript-in, freskoni sado pak njohuritë e juaja ose edhe përgatitu për intervisten tuaj të ardhshme! 💪 🚀! Përgjigjet gjenden në **seksionet e mbyllura** përfundi pyetjeve, thjesht kliko mbi to për të hapur seksionin e përgjigjeve. Është vetëm për argëtim, paç fat! ❤️ + +Mos hezitoni të më kontaktoni! 😊 +Instagram || Twitter || LinkedIn || Blog +
+ +| Ndjehuni të lirë të i përdorni në projektet e juaja |😃 Do të e vlerësoja shumë referencimin tuaj në ketë repositori, unë i krijoj pyetjet dhe poashtu edhe përgjigjet (lol) dhe komuniteti me ndihmon shumë të e përmirësoj dhe të mirëmbajë! 💪🏼 Faleminderit! + +--- + +
See 20 Available Translations 🇸🇦🇪🇬🇧🇦🇩🇪🇪🇸🇫🇷🇮🇩🇯🇵🇰🇷🇳🇱🇧🇷🇷🇺🇹🇭🇹🇷🇺🇦🇻🇳🇨🇳🇹🇼🇽🇰 +

+ +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](./sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) + +

+
+ +--- + +###### 1. Cila është vlera e saj? + +```javascript +function sayHi() { + console.log(name); + console.log(age); + var name = 'Lydia'; + let age = 21; +} + +sayHi(); +``` + +- A: `Lydia` dhe `undefined` +- B: `Lydia` dhe `ReferenceError` +- C: `ReferenceError` dhe `21` +- D: `undefined` dhe `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Brenda funksionit, fillimisht deklarojmë variablën `name` me fjalën kyçe `var`. Kjo do të thotë se variabla ngrihet - hoistohet (hapësira e memories caktohet gjatë fazës së krijimit) me vlerën e paracaktuar `undefined`, deri sa të arrijmë në rreshtin ku e definojmë variablën. Nuk kemi definuar ende variablën në rreshtin ku përpiqemi të shfaqim variablën `name`, kështu që ajo ende mban vlerën `undefined`. + +Variablat me fjalën kyçe `let` (dhe `const`) hoistohen, por ndryshe nga `var`, nuk inicializohen. Ato nuk janë të qasshme para rreshtit ku i deklarojmë (inicializojmë) ato. Kjo quhet "zona e vdekur temporale". Kur përpiqemi të iu qasemi variablave para se ato të jenë të deklaruara, JavaScript hedh një `ReferenceError`. + +

+
+ +--- + +###### 2. Cila është vlera e saj? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1); +} +``` + +- A: `0 1 2` dhe `0 1 2` +- B: `0 1 2` dhe `3 3 3` +- C: `3 3 3` dhe `0 1 2` + +
Përgjigja +

+ +#### Përgjigja: C + +Për shkak të ***event queque*** në JavaScript, funksioni callback `setTimeout` thirret pas ekzekutimit të unazës. Pasi që variabla `i` në iterimin e parë u deklarua duke përdorur fjalën kyçe `var`, kjo vlerë ishte globale. Gjatë unazës, ne rritëm vlerën e `i` me `1` çdo herë, duke përdorur operatorin unar `++`. Deri në kohën që funksioni callback `setTimeout` u thirr, `i` ishte e barabartë me `3` në unazën e parë. + +Në unazën e dytë, variabla `i` u deklarua duke përdorur fjalën kyçe `let`: variablat e deklaruara me fjalën kyçe `let` (dhe `const`) janë të qasshme në bllok (një bllok është çdo gjë mes `{ }`). Gjatë çdo iteracioni, `i` do të ketë një vlerë të re, dhe çdo vlerë është e qasshme brenda unazës. + +

+
+ +--- + +###### 3. Cila është vlera e saj? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2; + }, + perimeter: () => 2 * Math.PI * this.radius, +}; + +console.log(shape.diameter()); +console.log(shape.perimeter()); +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
Përgjigja +

+ +#### Përgjigja: B + +Vini re se vlera e `diameter` është një funksion i zakonshëm, ndërsa vlera e `perimeter` është një funksion shigjete (arrow function). + +Në funksionet shigjeta, fjala kyçe `this` referohet në qasjen në rrethinën aktuale përreth saj, ndryshe nga funksionet e zakonshme! Kjo do të thotë se kur ne e thërrasim `perimeter`, ajo nuk referohet tek objekti shape, por tek rrethina e saj (për shembull "window"). + +`radius` nuk ka ndonjë vlerë të caktuar në atë objekt, prandaj do të kemi si rezultat `NaN`. + +

+
+ +--- + +###### 4. Cila është vlera e saj? + +```javascript ++true; +!'Lydia'; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori unar `+` provon të e konvertojë operandin në numër. `true` është `1`, dhe `false` është `0`. + +Vargu i karaktereve (stringu) `'Lydia'` konsiderohet si vlerë `true`. Çfarë ne realisht po pyesim është "a është kjo vlerë e vërtetë e pavërtetë?". Kjo do të kthejë vlerën `false`. + +

+
+ +--- + +###### 5. Cila përgjigje është e saktë? + +```javascript +const bird = { + size: 'small', +}; + +const mouse = { + name: 'Mickey', + small: true, +}; +``` + +- A: `mouse.bird.size` nuk është sintaksë valide +- B: `mouse[bird.size]` nuk është sintaksë valide +- C: `mouse[bird["size"]]` nuk është sintaksë valide +- D: Të gjitha sintaksat janë valide + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, të gjithë çelësat (keys) e objektit janë stringje (përveç nëse është Symbol). Edhe nëse nuk i _shkruajmë_ si stringje, ato gjithmonë konvertohen në stringje në prapavijë. + +JavaScript interpreton deklarimet. Kur përdorim notacionin e kllapave, ai shikon kllapën e parë hapëse `[` dhe vazhdon derisa të gjejë kllapën mbyllëse `]`. Vetëm atëherë do të vlerësohet deklarata (kthehet vlera e caktuar për atë deklarim). + +`mouse[bird.size]`: Fillimisht gjendet vlera e `bird.size`, e cila është `"small"`. `mouse["small"]` kthen `true` + +Megjithatë, me notacionin pikë, kjo nuk ndodh. `mouse` nuk ka një çelës të quajtur `bird`, që do të thotë se `mouse.bird` është `undefined`. Pastaj, ne kërkojmë "size" duke përdorur notacionin pikë: "mouse.bird.size". Meqenëse `mouse.bird` është `undefined`, ne në fakt po pyesim 'undefined.size'. Kjo nuk është valide dhe do të marrim një gabim të ngjashëm me `Cannot read property "size" of undefined`. + +

+
+ +--- + +###### 6. Cila është vlera e saj? + +```javascript +let c = { greeting: 'Hey!' }; +let d; + +d = c; +c.greeting = 'Hello'; +console.log(d.greeting); +``` + +- A: `Hello` +- B: `Hey!` +- C: `undefined` +- D: `ReferenceError` +- E: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, të gjitha objektet ndërveprojnë me _referencë_ kur i vendosin me vlera të barabarta me njëri-tjetrin. + +Fillimisht, variabla `c` mbanë vlerën për një objekt. Më vonë, ne e caktojmë `d` me të njejtën reference të cilën `c` ka tek objekti. + + + +Kur e ndryshoni një objekt, i ndryshoni të gjitha objektet. + +

+
+ +--- + +###### 7. Cila është vlera e saj? + +```javascript +let a = 3; +let b = new Number(3); +let c = 3; + +console.log(a == b); +console.log(a === b); +console.log(b === c); +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +`new Number()` është konstruktor i integruar (built-in function). Edhe pse duket si një numër, nuk është në të vërtetë një numër: ai ka një mori karakteristikash shtesë dhe si rrjedhojë është një objekt. + +Kur përdorim operatorin `==` (operatorin i barazimit), ai kontrollon vetëm nëse ka të njëjtën _vlerë_. Të dy kanë vlerën `3`, kështu që kthen `true`. + +Megjithatë, kur përdorim operatorin `===` (operatori i barazisë strikte), të dy vlerat dhe tipi i tyre duhet të jenë të njëjta. Nuk është: `new Number()` nuk është një numër, është një __objekt__. Të dy kthejnë `false`. + +

+
+ +--- + +###### 8. Cila është vlera e saj? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor; + return this.newColor; + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor; + } +} + +const freddie = new Chameleon({ newColor: 'purple' }); +console.log(freddie.colorChange('orange')); +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: D + +Funksioni `colorChange` është statik. Metodat statike janë krijuar për të "jetuar" vetëm në konstruktorin në të cilin janë krijuar dhe nuk mund t'i kalohen asnjë fëmije ose të thirren në instancat e klasës. Meqenëse `freddie` është një instancë e klasës Chameleon, funksioni nuk mund të thirret. Në këtë rast do të kthehet `TypeError`. + +

+
+ +--- + +###### 9. Cila është vlera e saj? + +```javascript +let greeting; +greetign = {}; // Typo - gabim drejtëshkrimor! +console.log(greetign); +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Do të printojë objekt, sepse ne sapo krijuam një objekt bosh në objektin global! Kur e shkruajtëm gabim `greeting` si `greetign`, interpretuesi i JS në fakt e pa këtë si: + +1. `global.greetign = {}` në Node.js +2. `window.greetign = {}`, `frames.greetign = {}` dhe `self.greetign` në shfletues (browser). +3. `self.greetign` në web workers. +4. `globalThis.greetign` në të gjitha mjediset. + +Për të shmangur këtë, ne mund të përdorim `"use strict"`. Kjo siguron që ju të keni deklaruar një variabël përpara se ta vendosni atë të barabartë (inicializoni ndonjë variabël tjetër me vlerën e saj) me ndonjë gjë. + +

+
+ +--- + +###### 10. Çfarë do të ndodh kur e bëjmë këtë veprim? + +```javascript +function bark() { + console.log('Woof!'); +} + +bark.animal = 'dog'; +``` + +- A: Asgjë, gjithçka është në rregull! +- B: `SyntaxError`. Nuk mund të shtoni veti te një funksion në këtë mënyrë. +- C: `"Woof"` do të printohet. +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Kjo është e mundshme në JavaScript, spese funksionet janë objekte! (Gjithçka, përveç tipeve primitive janë objekte) + +Një funksion është një lloj i veçantë objekti. Kodi që shkruani vetë nuk është funksioni aktual. Funksioni është një objekt me veti. Kjo veti është e pavokueshme. + +

+
+ +--- + +###### 11. Cila është vlera e saj? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person('Lydia', 'Hallie'); +Person.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Në JavaScript, funksionet janë objekte dhe për këtë arsye metoda `getFullName` i shtohet vetë objektit të funksionit të konstruktorit. Për këtë arsye, ne mund të thërrasim `Person.getFullName()`, por `member.getFullName` do të kthejë `TypeError`. + +Nëse dëshironi që një metodë të jetë e qasshme për të gjitha instancat e objektit, duhet ta shtoni atë në vetinë e quajtur "prototype": + +```js +Person.prototype.getFullName = function() { + return `${this.firstName} ${this.lastName}`; +}; +``` + +

+
+ +--- + +###### 12. Cila është vlera e saj? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const lydia = new Person('Lydia', 'Hallie'); +const sarah = Person('Sarah', 'Smith'); + +console.log(lydia); +console.log(sarah); +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D: `Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Për `sarah`, ne nuk përdorëm fjalën kyçe `new`. Kur përdorim `new`, `this` i referohet objektit të ri bosh që krijojmë. Megjithatë, nëse nuk shtoni `new`, `this` i referohet **objektit global**! + +E cekëm se `this.firstName` është `"Sarah"` dhe `this.lastName` është `"Smith"`. Çfarë bëmë realisht është se ne e definuam `global.firstName = 'Sarah'` dhe `global.lastName = 'Smith'`. `sarah` vetë mbetet `undefined`, pasi ne nuk kthejmë ndonjë vlerë nga funksioni `Person`. + +

+
+ +--- + +###### 13. Cilat janë tri fazat e "event propagation"? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
Përgjigja +

+ +#### Përgjigja: D + +Gjatë fazës **capturing** (kapjes), eventi kalon nëpër elementet paraardhëse deri te elementi i synuar. Më pas arrin në elementin **target** (e synuar) dhe fillon **bubbling**. + + + +

+
+ +--- + +###### 14. Të gjitha objektet kanë prototipe. + +- A: e vërtetë +- B: e pavërtetë + +
Përgjigja +

+ +#### Përgjigja: B + +Të gjitha objektet kanë prototipe, me përjashtim të **objektit bazë**. Objekti bazë është objekti i krijuar nga përdoruesi, ose një objekt që krijohet duke përdorur fjalën kyçe "new". Objekti bazë ka qasje në disa metoda dhe veti, të tilla si `.toString`. Kjo është arsyeja pse ju mund të përdorni metoda të integruara të JavaScript! Të gjitha këto metoda janë të disponueshme në prototip. Megjithëse JavaScript nuk mund ta gjejë atë drejtpërdrejt në objektin tuaj, ai zbret në zinxhirin e prototipit dhe e gjen atje, gjë që e bën atë të qasshëm për ju. + +

+
+ +--- + +###### 15. Cila është vlera e saj? + +```javascript +function sum(a, b) { + return a + b; +} + +sum(1, '2'); +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
Përgjigja +

+ +#### Përgjigja: C + +JavaScript është gjuhë e shkruar në mënyrë dinamike __dynamically typed language__: ne nuk specifikojmë se çfarë tipe janë variablat e caktuara. Vlerat mund të konvertohen automatikisht në një tip tjetër pa e ditur ju dhe ky proces quhet _implicit type coercion_ (shndërrimi i tipit në mënyrë të nënkuptuar). __Coercion__ është shndërrimi nga një tip në një tjetër. + +Në këtë shembull, JavaScript konverton numrin `1` në string, në mënyrë që për funksionin të ketë kuptim dhe të kthejë një vlerë. Përgjatë mbledhjes të një tipi number (`1`) dhe një tipi string (`'2'`), numri trajtohet si string. Ne mund ti bashkojmë stringjet si `"Hello" + "World"`, kështu që ajo që po ndodh këtu është `"1" + "2"` e cila kthen "12"`. + +

+
+ +--- + +###### 16. Cila është vlera e saj? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
Përgjigja +

+ +#### Përgjigja: C + +**postfiks** operatori unar `++`: + +1. Kthen vlerën (kthen `0`) +2. Rrit vleren (numri tani është `1`) + +**prefiks** operatori unar `++`: + +1. Rrit vlerën (numri tani është `2`) +2. Kthen vlerën (kthen `2`) + +Prandaj rezultati që kthehet është `0 2 2`. + +

+
+ +--- + +###### 17. Cila është vlera e saj? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
Përgjigja +

+ +#### Përgjigja: B + +Nëse përdorni literale të shabllonit (template literals) të etiketuar, vlera e argumentit të parë është gjithmonë një array vlerash stringu. Argumentet e mbetura marrin vlerat e shprehjeve të vendosura në variablat e dhëna! + +

+
+ +--- + +###### 18. Cila është vlera e saj? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur testojmë barazinë, primitivet krahasohen me _vlerën_ e tyre, ndërsa objektet krahasohen me _referencën_ e tyre. JavaScript kontrollon nëse objektet kanë një referencë në të njëjtin vend në memorie. + +Dy objektet që po krahasojmë nuk e kanë këtë: objekti që kemi vendosur si parametër i referohet një vendndodhjeje të ndryshme në memorie nga objekti që kemi përdorur për të kontrolluar barazinë. + +Kjo tregon pse të dyja: `{ age: 18 } === { age: 18 }` dhe `{ age: 18 } == { age: 18 }` kthen `false`. + +

+
+ +--- + +###### 19. Cila është vlera e saj? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
Përgjigja +

+ +#### Përgjigja: C + +Parametri "rest" (`...args`) na lejon të "mbledhim" të gjitha argumentet e mbetura në një array. Një array është një objekt, kështu që `typeof args` kthen `“objekt”` + +

+
+ +--- + +###### 20. Cila është vlera e saj? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: C + +Me `"use strict"`, mund të siguroheni se nuk do të deklaroni variabla globale pa qëllim. Ne asnjëherë nuk e kemi deklaruar variablen `age`, dhe pasi ne e përdorim `"use strict"`, do të na kthehet një error reference. Në qoftesë nuk përdorim `"use strict"`, do të kishte funksionuar pasi vetia `age` do të ishte shtuar në objektin global. + +

+
+ +--- + +###### 21. Sa do të jetë vlera e `sum`? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
Përgjigja +

+ +#### Përgjigja: A + +`eval` vlerëson kodet që i pasohen si string. Nëse është një shprehje, si në këtë rast, ajo vlerëson shprehjen. Shprehja është `10 * 10 + 5`. Kjo kthen numrin '105'. + +

+
+ +--- + +###### 22. Sa kohë është e qasshme cool_secret? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: Përgjithmonë, e dhëna nuk humb. +- B: Kur përdoruesi mbyll dritaren. +- C: Kur përdoruesi mbyll browser-in në tërësi, jo vetëm dritaren. +- D: Kur përdoruesi ndal kompjuterin e tyre. + +
Përgjigja +

+ +#### Përgjigja: B + +Të dhënat e ruajtura në `sessionStorage` largohen pasi të mbyllet _dritarja_. + +Nëse keni përdorur 'localStorage', të dhënat do të kishin mbetur aty përgjithmonë, përveç nëse për shembull thirret 'localStorage.clear()'. + +

+
+ +--- + +###### 23. Cila është vlera e saj? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me fjalën kyçe `var`, mund të deklaroni shumë variabla me të njëjtin emër. Më pas variabla do të mbajë vlerën e fundit të inicializuar në të. + +Ju nuk mund ta bëni këtë me 'let' ose 'const' pasi ato kanë qasje në bllok (block-scoped). + +

+
+ +--- + +###### 24. Cila është vlera e saj? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Të gjitha çelësat e objektit (përjashto Simbolet) janë stringje në prapavijë, edhe nëse ju vetë nuk e shkruani atë si string. Kjo është arsyeja pse `obj.hasOwnProperty('1')` gjithashtu kthen vlerën true. + +Nuk funksionon në këtë mënyrë për një "set". Nuk ka asnjë `'1'` në set-in tonë: `set.has('1')` kthen `false`. Nëse ka tipin numër `1`, `set.has(1)` kthen `true`. + +

+
+ +--- + +###### 25. Cila është vlera e saj? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: C + +Nëse keni dy çelësa me të njëjtin emër, çelësi do të zëvendësohet. Do të jetë ende në pozitën e parë, por me vlerën e fundit të specifikuar. + +

+
+ +--- + +###### 26. Konteksti global i ekzekutimit në JavaScript krijon dy gjëra për ju: objektin global, dhe fjalën kyçe "this". + +- A: e vërtetë +- B: e pavërtetë +- C: varet + +
Përgjigja +

+ +#### Përgjigja: A + +Konteksti bazë i ekzekutimit është konteksti global i ekzekutimit: është ajo që është e qasshme kudo në kodin tuaj. + +

+
+ +--- + +###### 27. Cila është vlera e saj? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
Përgjigja +

+ +#### Përgjigja: C + +Deklarata `continue` kalon një iterim nëse një kusht i caktuar kthen `true`. + +

+
+ +--- + +###### 28. Cila është vlera e saj? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +`String` është një konstruktor i integruar, të cilit mund t'i shtojmë veti. Sapo shtuam një metodë në prototipin e saj. Stringjet primitive konvertohen automatikisht në një objekt string, të gjeneruara nga funksioni i prototipit të stringut. Pra, të gjitha vargjet (objektet e stringut) kanë qasje në atë metodë! + +

+
+ +--- + +###### 29. Cila është vlera e saj? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Çelësat e objekteve konvertohen automatikisht në stringje. Ne po provojmë të vendosim një objekt si çelës për objektin 'a', me vlerën '123'. + +Megjithatë, kur e përdorim "stringify" në një objekt, ai bëhet `"[object Object]"`. Pra, ajo që po themi këtu, është se `a["[object Object]"] = 123`. Pastaj, ne mund të provojmë të bëjmë të njëjtën gjë përsëri. `c` është një objekt tjetër që ne po e "stringify" në mënyrë implicite. Pra, atëherë, `a["[object Object]"] = 456`. + +Pastaj ne e printojmë `a[b]` e cila është `a["[object Object]"]`. We sapo e vendosëm `456` në të, prandaj edhe do të kthejë `456` + +

+
+ +--- + +###### 30. Cila është vlera e saj? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne kemi një funksion "setTimeout" të cilin e thirrëm së pari. Megjithatë, ai u printua i fundit. + +Kjo është për shkak se në browser-a, ne nuk kemi vetëm "runtime" funksionalitet, ne gjithashtu kemi diçka që quhet `WebAPI`. `WebAPI` na jep funksionin `setTimeout` dhe poashtu për shembull DOM. + +Pasi _callback_ të vendoset në WebAPI, vetë funksioni "setTimeout" (por jo callback!) del nga pirgu (stack). + + + +Tani `foo` thirret dhe `"First"` do të printohet. + + + +`foo` del nga stack, dhe `baz` thirret. `"Third"` do të printohet. + + + +WebAPI nuk mund të shtojë gjëra në stack sa herë që është gati. Në vend të kësaj, ai vendos callback në diçka që quhet _queue_. + + + +Këtu fillon të funksionojë event loop. Një **event loop** shikon "stack" dhe "task queue". Nëse "stack" është bosh, ai merr gjënë e parë në radhë dhe e vendos atë në stack. + + + +`bar` thirret, `"Second"` do të printohet dhe do të largohet nga stack. + +

+
+ +--- + +###### 31. Çfarë do të jetë event.target kur e klikojmë butonin? + +```html +
+
+ +
+
+``` + +- A: `div` i jashtëm +- B: `div` i brendshëm +- C: `button` +- D: Një array i elementeve të ndërthurura. + +
Përgjigja +

+ +#### Përgjigja: C + +Elementi më thellë i mbivendosur që shkaktoi ngjarjen është objektivi i ngjarjes. Ju mund të ndaloni bubbling me "event.stopPropagation". + +

+
+ +--- + +###### 32. Kur klikoni paragrafin, çfarë do të printohet në dalje? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
Përgjigja +

+ +#### Përgjigja: A + +Nëse klikojmë `p`, shohim dy dalje: `p` dhe `div`. Gjatë "event propagation", ekzistojnë 3 faza: kapja, objektivi dhe flluska. Si parazgjedhje, mbajtësit e ngjarjeve (event handlers) ekzekutohen në fazën e flluskimit (përveç nëse e vendosni "useCapture" në "true"). Ai shkon nga elementi më i thellë i mbivendosur jashtë. + +

+
+ +--- + +###### 33. Cila është vlera e saj? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
Përgjigja +

+ +#### Përgjigja: D + +Në të dy rastet, ne mund të e vendosim objektin si argument varësisht në cilin funksion dëshirojmë të referohemi me fjalën kyçe `this`. Megjithatë, `.call` gjithashtu ekzekutohet menjëherë! + +`.bind.` kthen një _kopje_ të funksionit, por me një kontekst të lidhur! Nuk ekzekutohet menjëherë. + +

+
+ +--- + +###### 34. Cila është vlera e saj? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
Përgjigja +

+ +#### Përgjigja: B + +Funksioni `sayHi` kthen vlerën e kthyer të shprehjes së funksionit të thirrur menjëherë (IIFE). Ky funksion ktheu `0`, që është i tipit `“numër”`. + +FYI: `typeof` mund të kthejë listën e mëposhtme të vlerave: `undefined`, `boolean`, `number`, `bigint`, `string`, `symbol`, `function` dhe `object`. Vini re se `typeof null` kthen `“object”`. + +

+
+ +--- + +###### 35. Cilat nga këto vlera janë false? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: Të gjitha paraqesin vlerë false + +
Përgjigja +

+ +#### Përgjigja: A + +Ekzistojnë këto 8 vlera të cilat paraqesin false: + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (string i zbrazët) +- `0` +- `-0` +- `0n` (BigInt(0)) + +Konstruktorët e funksioneve, si `new Number` dhe `new Boolean` kthejnë vlerë të vërtetë (truthy). + +

+
+ +--- + +###### 36. Cila është vlera e saj? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
Përgjigja +

+ +#### Përgjigja: B + +`typeof 1` kthen `"number"`. +`typeof "number"` kthen `"string"` + +

+
+ +--- + +###### 37. Cila është vlera e saj? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, null x 7, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, empty x 7, 11]` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur inicializoni një vlerë për një element të vargut (array) i cili e kalon gjatësinë e tij, Javascript-i krijon diçka që quhet "empty slots (vende të zbrazëta)". Këto realisht e kanë vlerën `undefined`, por ju do të shihni diçka si: + +`[1, 2, 3, empty x 7, 11]` + +varësisht ku e ekzekutoni kodin tuaj (dallon për çdo browser, node, etj.) + +

+
+ +--- + +###### 38. Cila është vlera e saj? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Blloku `catch` merr argumentin `x`. Kjo nuk është e njëjta `x` si variabla kur ne japim argumente. Variabla `x` (në bllokun `catch`) ka shtrirje blloku (është block-scoped). + +Më vonë, ne e inicializojmë këtë variabël me shtrirje blloku të barabartë me `1` dhe inicializojmë vlerën e ndryshores `y`. Tani, ne printojmë ndryshoren me shtrirje blloku `x`, e cila është e barabartë me `1`. + +Jashtë bllokut `catch`, `x` është ende `undefined`, dhe `y` është `2`. Kur dëshirojmë të bëjmë `console.log(x)` jashtë bllokut `catch`, do të kthejë `undefined`, dhe `y` kthen `2`. + +

+
+ +--- + +###### 39. Çdo gjë në JavaScript është ose... + +- A: primitive ose objekt +- B: funksion ose objekt +- C: pyetje me trik! vetëm objekt +- D: numër ose objekt + +
Përgjigja +

+ +#### Përgjigja: A + +JavaScript ka vetëm tipe primitive dhe objekte. + +Tipet primitive janë `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, dhe `symbol`. + +Ajo që e dallon një tip primitiv nga një objekt është se primitivët nuk kanë asnjë veti ose metodë; megjithatë, do të vini re se `foo.toUpperCase()` vlerësohet në `'FOO'` dhe nuk rezulton në `TypeError`. Kjo ndodh sepse kur përpiqeni të qasni një veçori ose metodë në një primitive si një string, JavaScript do të mbështjellë në mënyrë implicite tipin primitiv duke përdorur një nga klasat e mbështjellësit, d.m.th. `String`, dhe më pas do ta heqë menjëherë mbështjellësin pasi të vlerësohet shprehja. Të gjithë primitivët përveç `null` dhe `undefined` e shfaqin këtë sjellje. + +

+
+ +--- + +###### 40. Cila është vlera e saj? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
Përgjigja +

+ +#### Përgjigja: C + +`[1, 2]` është vlera jonë fillestare. Kjo është vlera me të cilën fillojmë, dhe vlera e parë e `acc`. Gjatë iterimit të parë, `acc` është `[1,2]`, dhe `cur` është `[0, 1]`. Ne i bashkojmë ato dhe kjo rezulton në `[1, 2, 0, 1]`. + +Pastaj, `[1, 2, 0, 1]` është `acc` dhe `[2, 3]` është `cur`. I bashkojmë ato dhe marrim `[1, 2, 0, 1, 2, 3]` + +

+
+ +--- + +###### 41. Cila është vlera e saj? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
Përgjigja +

+ +#### Përgjigja: B + +`null` është false. `!null` kthen `true`. `!true` kthen `false`. + +`""` është false. `!""` kthen `true`. `!true` kthen `false`. + +`1` është e vërtetë (truthy). `!1` kthen `false`. `!false` kthen `true`. + +

+
+ +--- + +###### 42. Çfarë do të kthejë në browser funksioni `setInterval`? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: një id unike +- B: numrin e milisekondave të specifikuara +- C: funksionin të cilin e kemi kaluar si argument +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Kthen një id unike. Kjo id mund të përdoret për të pastruar intervalin me funksionin `clearInterval()`. + +

+
+ +--- + +###### 43. Çfarë do të kthehet si rezultat? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
Përgjigja +

+ +#### Përgjigja: A + +Stringu është i iterueshëm. Operatori i përhapjes (spread operator) iteron çdo karakter të një elementi të iterueshëm në një element (në këtë rast array []). + +

+
+ +--- + +###### 44. Cila është vlera e saj? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksionet e rregullta nuk mund të ndalen në mes të ekzekutimit pas thirrjes. Sidoqoftë, funksioni i gjeneratorit (generator function) mund të "ndalohet" në mes të rrugës dhe më vonë të vazhdojë nga vendi ku ndaloi. Sa herë që një funksion gjenerues ndeshet me fjalën kyçe `yield`, funksioni jep vlerën e specifikuar pas saj. Vini re se funksioni i gjeneratorit në atë rast nuk e _kthen_ (return) vlerën, por e _jep_ (yield) vlerën. + +Së pari, ne inicializojmë funksionin e gjeneratorit me `i` të barabartë me `10`. Ne thërrasim funksionin e gjeneratorit duke përdorur metodën `next()`. Herën e parë që thërrasim funksionin e gjeneratorit, `i` është i barabartë me `10`. Ai ndeshet me fjalën kyçe të parë `yield`: jep vlerën e `i`. Gjeneratori tani është `në pauzë` dhe `10` regjistrohet. + +Pastaj, ne e thirrim funksionin përsëri me metodën `next()`. Fillon dhe vazhdon aty ku ka ndaluar më parë, ende me `i` të barabartë me `10`. Tani, ai ndeshet me fjalën kyçe tjetër "yield" dhe jep `i * 2`. `i` është e barabartë me `10`, kështu që kthen `10 * 2`, që është `20`. Kjo rezulton në `10, 20`. + +

+
+ +--- + +###### 45. Çfarë do të kthehet si rezultat? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Përgjigja +

+ +#### Përgjigja: B + +Kur i kalojmë premtime (promises) të shumta metodës `Promise.race`, ajo zgjidh/refuzon premtimin _e parë_ që do të zgjidhet/refuzohet. Me metodën `setTimeout`, kalojmë një kohëmatës: 500 ms për premtimin e parë (`firstPromise`) dhe 100 ms për premtimin e dytë (`secondPromise`). Kjo do të thotë se `secondPromise`zgjidhet fillimisht me vlerën `'two'`. `res` tani mban vlerën e `'two'`, e cila printohet. + +

+
+ +--- + +###### 46. Cila është vlera e saj? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Përgjigja +

+ +#### Përgjigja: D + +Së pari, deklarojmë variablën `person` me vlerën e objektit i cili e ka vetinë `name`. + + + +Më pas, ne deklarojmë një variabël të quajtur `members`. E caktojmë elementin e parë të atij array të barabartë me vlerën e variablës `person`. Objektet ndërveprojnë me _referencë_ kur i vendosin të barabartë me njëri-tjetrin. Kur caktoni një referencë nga një ndryshore në tjetrën, ju bëni një _kopje_ të asaj reference. (vini re se ato nuk kanë të njëjtën referencë!) + + + +Pastaj e ri-inicializojmë variablën `person` të barabartë me `null` + + + +Ne po e modifikojmë vetëm vlerën e variblës `person`, dhe jo të elementit të parë ne array, meqenëse ai element ka një referencë të ndryshme (të kopjuar) për objektin. Elementi i parë në `members` ende mban referencën e tij ndaj objektit origjinal. Kur printojmë array `members`, elementi i parë ende mban vlerën e objektit, i cili printohet. + +

+
+ +--- + +###### 47. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
Përgjigja +

+ +#### Përgjigja: B + +Me unazën `for-in`, ne mund të iterojmë përgjatë çelësave të objektit, në këtë rast `name` dhe `age`. Në prapavijë, çelësat e objektit janë stringje (në qoftesë nuk janë Symbol). Në çdo unazë, ne vendosim vlerën e `item` të barabartë me çelësin aktual në të cilin po iterohet. Së pari, `item` është i barabartë me `name`, dhe printohet. Pastaj, `item` është e barabartë me `age` dhe printohet. + +

+
+ +--- + +###### 48. Cila është vlera e saj? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
Përgjigja +

+ +#### Përgjigja: B + +Radha e veprimeve matematikore të operatorit është rendi në të cilin përpiluesi (kompajleri) vlerëson shprehjet, qoftë nga e majta në të djathtë ose nga e djathta në të majtë. Kjo ndodh vetëm nëse të gjithë operatorët kanë përparësinë _të njejtë_. Ne kemi vetëm një lloj operatori: `+`. Për më tepër, radha e veprimeve matematikore është nga e majta në të djathtë. + +`3 + 4` llogaritet së pari. Kjo rezulton në numrin `7`. + +`7 + '5'` rezulton në `"75"` për shkak të shndërrimit të tipit (coercion). JavaScript-i e konverton numrin `7` ne një string, shiko pyetjen 15. Ne mund të i bashkojmë dy stringje duke e përdorur operatorin `+`. `"7"` + `"5"` rezulton në `"75"` + +

+
+ +--- + +###### 49. What's the value of `num`? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
Përgjigja +

+ +#### Përgjigja: C + +Kthehen vetëm numrat e parë në string. Bazuar në _radix (bazë)_ (argumenti i dytë për të specifikuar se në çfarë tipi duam ta parsojmë atë: bazën 10, heksadecimal, oktal, binar, etj.), `parseInt` kontrollon nëse karakteret në string janë të vlefshme. Pasi të ndeshet me një karakter që nuk është një numër i vlefshëm në bazë, ai ndalon parsimin dhe injoron karakteret e ardhshme. + +`*` nuk është numër valid. Parson vetëm `"7"` në decimal `7`. `num` tani mban vlerën `7`. + +

+
+ +--- + +###### 50. Cila është vlera e saj? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
Përgjigja +

+ +#### Përgjigja: C + +Kur iterojmë (map-ojmë) një array, vlera e `num` është e barabartë me elementin që është duke u iteruar aktualisht. Në këtë rast, elementet janë numra, kështu që kushti i deklaratës if `typeof num === "number"` kthen `true`. Funksioni map krijon një grup të ri dhe fut vlerat e kthyera nga funksioni. + +Megjithatë, ne nuk kthejmë një vlerë. Kur nuk kthejmë një vlerë nga funksioni, funksioni kthen `undefined`. Për çdo element në array, blloku i funksionit thirret, kështu që për secilin element ne kthejmë `undefined`. + +

+
+ +--- + +###### 51. Cila është vlera e saj? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
Përgjigja +

+ +#### Përgjigja: A + +Argumentet kalohen si _vlerë_, përveç nëse vlera e tyre është një objekt, atëherë ato kalohen si _referencë_. `birthYear` kalohet sipas vlerës, pasi është një string, jo një objekt. Kur kalojmë argumente sipas vlerës, krijohet një _kopje_ e asaj vlere (shih pyetjen 46). + +Variabla `birthYear` ka referencë në vlerën `“1997”`. Argumenti `year` gjithashtu ka referencë në vlerën `"1997"`, por nuk është e njëjta vlerë si `birthYear`. Kur përditësojmë vlerën e `year` duke vendosur `year` të barabartë me `"1998"`, ne po përditësojmë vetëm vlerën e `year`. `birthYear` është ende i barabartë me `"1997"`. + +Vlera e `person` është objekt. Argumenti `member` ka referencë (të kopjuar) për objektin e njejtë. Kur modifikojmë një veti të objektit që `member` ka një referencë, vlera e `person` gjithashtu do të modifikohet, pasi të dy kanë një referencë për të njëjtin objekt. Vetia `name` e `person` tani është e barabartë me vlerën `"Lydia"`. + +

+
+ +--- + +###### 52. Cila është vlera e saj? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
Përgjigja +

+ +#### Përgjigja: D + +Me deklaratën `throw`, ne mund të krijojmë gabime (error) të personalizuara. Me këtë deklaratë, ju mund të bëni përjashtime. Një përjashtim mund të jetë një string, një numër, një boolean ose një objekt. Në këtë rast, përjashtimi ynë është stringy `'Hello world!'`. + +Me deklaratën `catch`, ne mund të specifikojmë se çfarë të bëjmë nëse një përjashtim hidhet në bllokun `try`. Bëhet një përjashtim: stringu `'Hello world!'`. `e` tani është e barabartë me atë string, të cilin e regjistrojmë. Kjo rezulton në `'Oh an error: Hello world!'`. + +

+
+ +--- + +###### 53. Cila është vlera e saj? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: B + +Kur një konstruktor thirret me fjalën kyçe `new`, ai krijon një objekt dhe vendos fjalën kyçe `this` për t'iu referuar atij objekti. Si parazgjedhje, nëse konstruktori nuk kthen asgjë në mënyrë të qartë, ai do të kthejë objektin e krijuar së fundi. + +Në këtë rast, konstruktori `Car` kthen në mënyrë eksplicite një objekt të ri me `make` të vendosur në `"Maserati"`, i cili mbishkruan sjelljen e paracaktuar. Prandaj, kur thirret `New Car()`, objekti i kthyer i caktohet `myCar`, duke rezultuar në daljen `“Maserati”` kur qaset `myCar.make`. + +

+
+ +--- + +###### 54. Cila është vlera e saj? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
Përgjigja +

+ +#### Përgjigja: A + +`let x = (y = 10);` është shkurtesë për: + +```javascript +y = 10; +let x = y; +``` + +Kur e vendosim `y` të barabartë me `10`, ne në të vërtetë e shtojmë vetinë `y` në objektin global (`window` në browser, `global` në Node). Në browser, `window.y` është tani e barabartë me `10`. + +Më pas, ne deklarojmë variablën `x` me vlerën `y`, e cila është `10`. Variablat e deklaruara me fjalën kyçe 'let' janë _block scoped_, ato përcaktohen vetëm brenda bllokut ku janë deklaruar; shprehja e funksionit të thirrur menjëherë (IIFE) në këtë rast. Kur përdorim operatorin `typeof`, operandi `x` nuk është i përcaktuar: ne po përpiqemi të qasim `x` jashtë bllokut ku ai është deklaruar. Kjo do të thotë se `x` nuk është përcaktuar. Vlerat e të cilave nuk u është caktuar një vlerë ose nuk janë deklaruar janë të tipit `"undefined"`. `console.log(typeof x)` kthen `"undefined"`. + +Megjithatë, ne krijuam një variabël globale `y` kur vendosëm `y` të barabartë me `10`. Kjo vlerë është e qasshme kudo në kodin tonë. `y` është përcaktuar dhe mban vlerën e tipit `"number"`. `console.log(typeof y)` kthen `"number"`. + +

+
+ +--- + +###### 55. Cila është vlera e saj? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne mund të fshijmë veti nga objektet duke përdorur fjalën kyçe `delete`, gjithashtu në prototip. Duke fshirë një veti në prototip, ajo nuk është më e qasshme në zinxhirin e prototipit. Në këtë rast, funksioni `bark` nuk është më i qasshëm në prototip pas `delete Dog.prototype.bark`, por ne ende provojmë të i qasemi. + +Kur përpiqemi të thërrasim diçka që nuk është funksion, hidhet një 'TypeError'. Në këtë rast `TypeError: pet.bark is not a function`, pasi `pet.bark` është `undefined`. + +

+
+ +--- + +###### 56. Cila është vlera e saj? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
Përgjigja +

+ +#### Përgjigja: D + +Objekti `Set` është një koleksion vlerash _unike_: një vlerë mund të paraqitet vetëm një herë në një grup (set). + +Vendosëm `[1, 1, 2, 3, 4]` me një vlerë dublikate `1`. Meqenëse nuk mund të kemi dy vlera të njëjta në një "set", njëra prej tyre largohet. Kjo rezulton në `{1, 2, 3, 4}`. + +

+
+ +--- + +###### 57. Cila është vlera e saj? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
Përgjigja +

+ +#### Përgjigja: C + +Një modul i importuar mund vetëm të i lexohet vlera (_read-only_): nuk mund të modifikohet. Vetëm moduli i cili i importon ato mund të ndërrojë atë vlerë. + +Kur tentojmë të rrisim vlerën e `myCounter`, do të marrim një error: `myCounter` mundet vetëm të lexohet dhe nuk mund të modifikohet. + +

+
+ +--- + +###### 58. Cila është vlera e saj? + +```javascript +const name = 'Lydia'; +age = 21; + +console.log(delete name); +console.log(delete age); +``` + +- A: `false`, `true` +- B: `"Lydia"`, `21` +- C: `true`, `true` +- D: `undefined`, `undefined` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori "delete" kthen një vlerë booleane: `true` në fshirje të suksesshme, përndryshe do të kthejë `false`. Megjithatë, variablat e deklaruara me fjalën kyçe `var`, `const` ose `let` nuk mund të fshihen duke përdorur operatorin `delete`. + +Variabla `name` u deklarua me fjalën kyçe `const`, kështu që fshirja e saj nuk ishte e suksesshme: u kthye `false`. Kur vendosëm `age` të barabartë me `21`, ne në fakt shtuam një veti të quajtur `age` në objektin global. Ju mund të fshini me sukses vetitë nga objektet në këtë mënyrë, gjithashtu edhe objektin global, kështu që `delete age` kthen `true`. + +

+
+ +--- + +###### 59. Cila është vlera e saj? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
Përgjigja +

+ +#### Përgjigja: C + +Ne mund të targetojmë vlerat nga vargjet ose vetitë nga objektet përmes destrukturimit. Për shembull: + +```javascript +[a, b] = [1, 2]; +``` + + + +Vlera `a` tani është `1`, dhe vlera `b` tani është `2`. Çfarë ne bëmë në të vërtetë në pyetje, është: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +Kjo do të thotë se vlera e `y` është e barabartë me vlerën e parë në array, që është numri `1`. Kur printojmë `y`, do të kthehet `1`. + +

+
+ +--- + +###### 60. Cila është vlera e saj? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
Përgjigja +

+ +#### Përgjigja: B + +Është e mundur të kombinohen objektet duke përdorur operatorin e përhapjes (spread) `...`. Kjo ju lejon të krijoni kopje të çifteve çelës/vlerë të një objekti dhe t'i shtoni ato në një objekt tjetër. Në këtë rast, ne krijojmë kopje të objektit `user` dhe i shtojmë ato në objektin `admin`. Objekti `admin` tani përmban çiftet e kopjuara të çelësit/vlerës, që rezulton në `{ admin: true, emri: "Lydia", mosha: 21 }`. + +

+
+ +--- + +###### 61. Cila është vlera e saj? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
Përgjigja +

+ +#### Përgjigja: B + +Me metodën `defineProperty`, ne mund të shtojmë veti të reja në një objekt, ose të modifikojmë ato ekzistuese. Kur shtojmë një veti në një objekt duke përdorur metodën `defineProperty`, ato janë si parazgjedhje _not enumerable_. Metoda `Object.keys` kthen të gjithë emrat e vetive _numerable_ nga një objekt, në këtë rast vetëm `"name"`. + +Vetitë e shtuara duke përdorur metodën `defineProperty` janë të pandryshueshme si parazgjedhje. Ju mund ta mbishkruani këtë sjellje duke përdorur veçoritë `writable`, `configurable` dhe `enumerable`. Në këtë mënyrë, metoda `defineProperty` ju jep shumë më tepër kontroll mbi vetitë që po i shtoni një objekti. + +

+
+ +--- + +###### 62. Cila është vlera e saj? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
Përgjigja +

+ +#### Përgjigja: A + +Argumenti i dytë i "JSON.stringify" është _zëvendësuesi_. Zëvendësuesi mund të jetë ose një funksion ose një array, dhe ju lejon të kontrolloni se çfarë dhe si duhet të konvertohet një vlerë e JavaScript në JSON string. + +Nëse zëvendësuesi është një _array_, vetëm emrat e vetive të përfshira në array do të shtohen në stringun JSON. Në këtë rast, përfshihen vetëm vetitë me emrat `"level"` dhe `"health"`, përjashtohet `"username"`. `data` tani është e barabartë me `"{"level":19, "health":90}"`. + +Nëse zëvendësuesi është një _funksion_, ky funksion thirret në çdo veti në objektin që po e përdorni metodën 'stringify'. Vlera e kthyer nga ky funksion do të jetë vlera e vetive kur të shtohet në vargun JSON. Nëse vlera është `undefined`, kjo veti përjashtohet nga vargu JSON. + +

+
+ +--- + +###### 63. Cila është vlera e saj? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
Përgjigja +

+ +#### Përgjigja: A + +Operatori unar `++` fillimisht kthen vlerën e operandit, pastaj e rrit vlerën e tij. Vlera e `num1` është `10`, meqenëse funksioni `increaseNumber` fillimisht kthen vlerën e `num`, e cila është `10`, dhe vetëm pastaj e rrit vlerën e `num`. + +`num2` është `10`, pasi ne e kaluam `num1` si argument tek `increasePassedNumber`. `number` është i barabartë me `10`(vlera e `num1`). Përsëri, operatori unar `++` _së pari kthen_ vlerën e operandit, dhe pastaj rrit vlerën e tij. Vlera e `number` është `10`, kështu që `num2` është e barabartë me `10`. + +

+
+ +--- + +###### 64. Cila është vlera e saj? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
Përgjigja +

+ +#### Përgjigja: C + +Në ES6, ne mund të inicializojmë parametrat me një vlerë të paracaktuar (default). Vlera e parametrit do të jetë vlera e paracaktuar, nëse asnjë vlerë tjetër nuk i është kaluar funksionit, ose nëse vlera e parametrit është `"undefined"`. Në këtë rast, ne i shpërndajmë vetitë e objektit `value` në një objekt të ri, kështu që `x` ka vlerën e paracaktuar të `{ number: 10 }`. + +Argumenti i paracaktuar vlerësohet (llogaritet) në _kohën e thirrjes_! Sa herë që thërrasim funksionin, krijohet një objekt i ri. Ne e thërrasim funksionin `multiply` dy herët e para pa kaluar vlerën: `x` ka vlerën e paracaktuar të `{ number: 10 }`. Më pas printojmë vlerën e shumëzuar të atij numri, që është `20`. + +Herën e tretë që thërrasim funksionin `multiply`, kalojmë një argument: objektin e quajtur `value`. Operatori `*=` është në fakt shkurtesë për `x.number = x.number * 2`: ne e modifikojmë vlerën e `x.number` dhe printojmë vlerën e shumëzuar `20`. + +Herën e katërt, ne e kalojmë përsëri objektin `value`. `x.number` është modifikuar më parë në `20`, kështu që `x.number *= 2` printon `40`. + +

+
+ +--- + +###### 65. Cila është vlera e saj? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` dhe `3` `3` dhe `6` `4` +- B: `1` `2` dhe `2` `3` dhe `3` `4` +- C: `1` `undefined` dhe `2` `undefined` dhe `3` `undefined` dhe `4` `undefined` +- D: `1` `2` dhe `undefined` `3` dhe `undefined` `4` + +
Përgjigja +

+ +#### Përgjigja: D + +Argumenti i parë që merr metoda `reduce` është _akumulatori_, në këtë rast `x`. Argumenti i dytë është _vlera aktuale_, `y`. Me metodën e reduktimit, ne ekzekutojmë një funksion të kthimit (callback) në çdo element në array, i cili përfundimisht mund të rezultojë në një vlerë të vetme. + +Në këtë shembull, ne nuk jemi duke kthyer ndonjë vlerë, jemi vetëm duke printuar vlerat e akumulatorit dhe vlerën aktuale. + +Vlera e akumulatorit është e barabartë me vlerën e kthyer më parë të funksionit të kthimit (callback). Nëse nuk e kaloni argumentin opsional `initialValue` në metodën `reduce`, akumuluesi është i barabartë me elementin e parë në thirrjen e parë. + +Në thirrjen e parë, akumuluesi (`x`) është `1`, dhe vlera aktuale (`y`) është `2`. Ne nuk kthehemi nga callback, ne printojmë akumuluesin dhe vlerën aktuale: `1` dhe `2` printohen. + +Nëse nuk ktheni një vlerë nga një funksion, ai kthen `undefined`. Në thirrjen tjetër, akumuluesi është `undefined` dhe vlera aktuale është `3`. `undefined` dhe `3` printohet. + +Në thirrjen e katërt, ne përsëri nuk kthehemi nga callback. Akumulatori është përsëri `undefined` dhe vlera aktuale është `4`. `undefined` dhe `4` printohen. + +

+
+ +--- + +###### 66. Me cilin konstruktor mund të zgjerojmë me sukses klasën 'Dog'? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Përgjigja +

+ +#### Përgjigja: B + +Në një klasë të derivuar, ju nuk mund të përdorni fjalën kyçe `this` përpara se të e thirrni `super`. Nëse provoni ta bëni këtë, do të jap `ReferenceError`: 1 dhe 4 do të hedhin një gabim referimi. + +Me fjalën kyçe `super`, ne e thërrasim konstruktorin e asaj klase mëmë me argumentet e dhëna. Konstruktori i prindit merr argumentin `name`, kështu që ne duhet të kalojmë `name` në `super`. + +Klasa `Labrador` merr dy argumente, `name` meqenëse trashëgon klasën 'Dog', dhe `size` si një veti shtesë në klasën `Labrador`. Ata të dy duhet t'i kalojnë konstruktorit në `Labrador`, i cili implementohet saktë duke përdorur konstruktorin 2. + +

+
+ +--- + +###### 67. Cila është vlera e saj? + +```javascript +// index.js +console.log('running index.js'); +import { sum } from './sum.js'; +console.log(sum(1, 2)); + +// sum.js +console.log('running sum.js'); +export const sum = (a, b) => a + b; +``` + +- A: `running index.js`, `running sum.js`, `3` +- B: `running sum.js`, `running index.js`, `3` +- C: `running sum.js`, `3`, `running index.js` +- D: `running index.js`, `undefined`, `running sum.js` + +
Përgjigja +

+ +#### Përgjigja: B + +Me fjalën kyçe `import`, të gjitha modulet e importuara parsohen fillimisht (_para-parsed_). Kjo do të thotë që modulet e importuara ekzekutohen _të parat_, kodi në file që importon modulin ekzekutohet _më pas_. + +Ky është një dallimi në mes `require()` në CommonJS dhe `import`! Me `require()`, mund të ngarkoni varësitë sipas kërkesës gjatë ekzekutimit të kodit. Nëse do të kishim përdorur `require` në vend të `import`, `running index.js`, `running sum.js`, `3` do të ishte printuar në tastierë. + +

+
+ +--- + +###### 68. Cila është vlera e saj? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
Përgjigja +

+ +#### Përgjigja: A + +Çdo Symbol është tërësisht unik. Arsyeja e jepjes të argumentit në Symbol është të i jap përshkrim Symbol. Vlera e Symbol nuk është e varur nga argumenti i cili i ipet. Meqenëse po testojmë barazueshmërinë, ne jemi duke krijuar dy Symbol tërësisht të reja: `Symbol('foo')` i parë dhe `Symbol('foo)` i dytë. Të dy janë vlera unike dhe jo të barabarta me njëra tjetrën, `Symbol('foo') === Symbol('foo')` kthen `false`. + +

+
+ +--- + +###### 69. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; +console.log(name.padStart(13)); +console.log(name.padStart(2)); +``` + +- A: `"Lydia Hallie"`, `"Lydia Hallie"` +- B: `" Lydia Hallie"`, `" Lydia Hallie"` (`"[13x whitespace]Lydia Hallie"`, `"[2x whitespace]Lydia Hallie"`) +- C: `" Lydia Hallie"`, `"Lydia Hallie"` (`"[1x whitespace]Lydia Hallie"`, `"Lydia Hallie"`) +- D: `"Lydia Hallie"`, `"Lyd"`, + +
Përgjigja +

+ +#### Përgjigja: C + +Me metodën `padStart`, mund të shtojmë mbushje (padding) në fillim të një stringu. Vlera e kaluar në këtë metodë është gjatësia totale e stringut së bashku me mbushjen. Vargu "Lydia Hallie" ka një gjatësi prej `12` karakteresh. `name.padStart(13)` vendos 1 hapësirë në fillim të vargut, sepse 12 + 1 është 13. + +Nëse argumenti i kaluar në metodën `padStart` është më i vogël se gjatësia e array, nuk do të shtohet asnjë mbushje. + +

+
+ +--- + +###### 70. Cila është vlera e saj? + +```javascript +console.log('🥑' + '💻'); +``` + +- A: `"🥑💻"` +- B: `257548` +- C: Një varg që përmban kodin për t'i shfaqur këto simbole +- D: Error + +
Përgjigja +

+ +#### Përgjigja: A + +Me operatorin `+`, ju mund të bashkoni vargjet. Në këtë rast, ne po bashkojmë stringun `"🥑"` me stringun `"💻"`, duke rezultuar në `"🥑💻"`. + +

+
+ +--- + +###### 71. How can we log the values that are commented out after the console.log statement? + +```javascript +function* startGame() { + const Përgjigja = yield 'Do you love JavaScript?'; + if (Përgjigja !== 'Yes') { + return "Oh wow... Guess we're done here"; + } + return 'JavaScript loves you back ❤️'; +} + +const game = startGame(); +console.log(/* 1 */); // Do you love JavaScript? +console.log(/* 2 */); // JavaScript loves you back ❤️ +``` + +- A: `game.next("Yes").value` dhe `game.next().value` +- B: `game.next.value("Yes")` dhe `game.next.value()` +- C: `game.next().value` dhe `game.next("Yes").value` +- D: `game.next.value()` dhe `game.next.value("Yes")` + +
Përgjigja +

+ +#### Përgjigja: C + +Një funksion gjenerues (generator function) "pauzon" ekzekutimin e tij kur sheh fjalën kyçe `yield`. Së pari, duhet ta lëmë funksionin të japë vargun "A ju pëlqen JavaScript?", i cili mund të bëhet duke thirrur `game.next().value`. + +Çdo rresht ekzekutohet derisa të gjejë fjalën kyçe të parë "yield". Ekziston një fjalë kyçe `yield` në rreshtin e parë brenda funksionit: ekzekutimi ndalon me yield-in e parë! _Kjo do të thotë se variabla `Përgjigja` nuk është përcaktuar ende!_ + +Kur e thërrasim `game.next("Po").value`, `yield` i mëparshëm zëvendësohet me vlerën e parametrave të kaluar në funksionin `next()`, `"Yes"` në këtë rast. Vlera e ndryshores `Përgjigja` tani është e barabartë me `"Yes"`. Kushti i deklaratës if kthehet `false`, dhe `JavaScript loves you back ❤️` printohet. + +

+
+ +--- + +###### 72. Cila është vlera e saj? + +```javascript +console.log(String.raw`Hello\nworld`); +``` + +- A: `Hello world!` +- B: `Hello`      `world` +- C: `Hello\nworld` +- D: `Hello\n`      `world` + +
Përgjigja +

+ +#### Përgjigja: C + +`String.raw` kthen një varg ku karakteret speciale (`\n`, `\v`, `\t` etj.) injorohen! Vizat e pasme mund të jenë një problem pasi mund të përfundoni me diçka si: + +`const path = `C:\Documents\Projects\table.html`` + +E cila do të rezultonte në: + +`"C:DocumentsProjects able.html"` + +Me `String.raw`, vetëm do e injoronte karakterin special dhe do të printonte: + +`C:\Documents\Projects\table.html` + +Në këtë rast, `Hello\nworld` do të printohet. + +

+
+ +--- + +###### 73. Cila është vlera e saj? + +```javascript +async function getData() { + return await Promise.resolve('I made it!'); +} + +const data = getData(); +console.log(data); +``` + +- A: `"I made it!"` +- B: `Promise {: "I made it!"}` +- C: `Promise {}` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Një funksion asinkron gjithmonë kthen një "promise". `await` duhet të pres për funksionin "promise" te zgjidhjet: një "promise" në pritje do të kthehet kur e thirrim `getData()` në mënyrë që të vendosim `data` në të. + +Nëse do të dëshironim të kemi qasje në vlerën e zgjidhur `"I made it"` do të kishim përdorur metodën `.then()` në `data`: + +`data.then(res => console.log(res))` + +Kjo do të printonte `"I made it!"` + +

+
+ +--- + +###### 74. Cila është vlera e saj? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Metoda `.push()` kthen _gjatësinë_ e vargut "array" të ri! Më parë, array përmbante një element (stringun `"banana"`) dhe kishte gjatësinë `1`. Pasi shtuam stringun `"apple"` në array, ai do të përmbajë dy elemente dhe do të ketë gjatësinë `2`. Kjo kthehet nga funksioni `addToList`. + +Metoda `push` modifikon array origjinal. Në qoftëse ju dëshironi të ktheni _array_ nga funksioni në vend të _gjatësisë së vargut_, ateherë ju duhet të ktheni `list` pasi e vendosni `item` në të. + +

+
+ +--- + +###### 75. Cila është vlera e saj? + +```javascript +const box = { x: 10, y: 20 }; + +Object.freeze(box); + +const shape = box; +shape.x = 100; + +console.log(shape); +``` + +- A: `{ x: 100, y: 20 }` +- B: `{ x: 10, y: 20 }` +- C: `{ x: 100 }` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +`Object.freeze` e bën të pamundur shtimin, largimin ose modifikimin e vetive në një objekt (përveç nëse vlera e një vetie është një objekt tjetër). + +Kur krijojmë ndryshoren `shape` dhe e vendosim të barabartë me objektin e ngrirë `box`, `shape` i referohet gjithashtu një objekti të ngrirë. Ju mund të kontrolloni nëse një objekt është i ngrirë duke përdorur `Object.isFrozen`. Në këtë rast, `Object.isFrozen(shape)` do të kthehej e vërtetë, pasi variabla `shape` ka një referencë për një objekt të ngrirë. + +Meqenëse `shape` është e ngrirë dhe meqenëse vlera e `x` nuk është një objekt, ne nuk mund të modifikojmë vetinë `x`. `x` është ende e barabartë me `10` dhe `{ x: 10, y: 20 }` do të printohet. + +

+
+ +--- + +###### 76. Cila është vlera e saj? + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; + +console.log(firstName); +``` + +- A: `"Lydia"` +- B: `"myName"` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Duke përdorur [sintaksen e funksioneve destruktuese](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ne mund të targetojmë vlerat nga vargjet, ose vetitë nga objektet, në variabla të veçanta: + +```javascript +const { firstName } = { firstName: 'Lydia' }; +// versioni i ES5: +// var firstName = { firstName: 'Lydia' }.firstName; + +console.log(firstName); // "Lydia" +``` + +Gjithashtu, një veti mund të targetohet nga një objekt dhe t'i caktohet një variableje me një emër të ndryshëm nga vetia e objektit: + +```javascript +const { firstName: myName } = { firstName: 'Lydia' }; +// versioni i ES5: +// var myName = { firstName: 'Lydia' }.firstName; + +console.log(myName); // "Lydia" +console.log(firstName); // Uncaught ReferenceError: firstName is not defined +``` + +Prandaj, `firstName` nuk ekziston si variabël, kështu që tentimi për të qasur vlerën e saj do të ngrejë një `ReferenceError`. + +**Shënim:** Kujdes nga vetitë e `global scope`: + +```javascript +const { name: myName } = { name: 'Lydia' }; + +console.log(myName); // "lydia" +console.log(name); // "" ----- Browser psh. Chrome +console.log(name); // ReferenceError: name is not defined ----- NodeJS + +``` + +Kurdo që JavaScript nuk mundet të gjejë një varibël në _current scope_, ngrihet në [Scope chain](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md) dhe kërkon për të dhe në qoftëse e arrin nivelin më të lartë të shtrirjes (the top-level scope), të quajtur __Global scope__, dhe ende nuk e gjen do të ngrejë `ReferenceError`. + +- Në __Browsers__ si _Chrome_, `name` është _vetia e shtrirjes globale e vjetëruar_. Në këtë shembull, kodi funksionon brenda _global scope_ dhe nuk ka asnjë variabël lokale të përcaktuar nga përdoruesi për `name`, prandaj ai kërkon _variables/properties_ të paracaktuara në shtrirjen globale, në këtë rast shfletuesve, ai kërkon përmes objektit `window`, dhe do të nxjerrë vlerën [window.name](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) e cila është e barabartë me një varg __bosh__. +- Në __NodeJS__, nuk ka një veçori të tillë në objektin `global`, kështu që përpjekja për të iu qasur një variable joekzistente do të ngrejë një [ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined). + +

+
+ +--- + +###### 77. A është ky një funksion i pastër? + +```javascript +function sum(a, b) { + return a + b; +} +``` + +- A: Po +- B: Jo + +
Përgjigja +

+ +#### Përgjigja: A + +Një funksion është gjithmonë funksion i pastër nëse sa herë që i kalojmë argumente të njëjta gjithmonë kthen rezultatin e njëjtë. + +Funksioni `sum` _gjithmonë_ kthen të njëjtin rezultat. Nëse i kalojmë `1` dhe `2`, gjithmonë do të kthejë `3` pa ndonjë efekt anësorë. Nëse i kalojmë `5` dhe `10`, gjithmonë do të kthejë `15`, e kështu me radhë. Ky është definicioni i një funksioni të pastër. + +

+
+ +--- + +###### 78. Cila është vlera e saj? + +```javascript +const add = () => { + const cache = {}; + return num => { + if (num in cache) { + return `From cache! ${cache[num]}`; + } else { + const result = num + 10; + cache[num] = result; + return `Calculated! ${result}`; + } + }; +}; + +const addFunction = add(); +console.log(addFunction(10)); +console.log(addFunction(10)); +console.log(addFunction(5 * 2)); +``` + +- A: `Calculated! 20` `Calculated! 20` `Calculated! 20` +- B: `Calculated! 20` `From cache! 20` `Calculated! 20` +- C: `Calculated! 20` `From cache! 20` `From cache! 20` +- D: `Calculated! 20` `From cache! 20` `Error` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni `add` është një funksion _memoized_. Me memoizim, ne mund të ruajmë rezultatet e një funksioni në mënyrë që të përshpejtojmë ekzekutimin e tij. Në këtë rast, ne krijojmë një objekt `cache` që ruan vlerat e kthyera më parë. + +Nëse e thirrim sërish funksionin `addFunction` me të njëjtin argument, ai fillimisht kontrollon nëse e ka marrë tashmë atë vlerë në cache-in e tij. Nëse është kështu, vlera e caches do të kthehet, e cila kursen kohën e ekzekutimit. Përndryshe, nëse nuk është i ruajtur në memorie, ai do të llogarisë vlerën dhe do ta ruajë atë më pas. + +Ne e thirrim funksionin `addFunction` tre herë me të njëjtën vlerë: në thirrjen e parë, vlera e funksionit kur `num`" është e barabartë me `10` nuk është ruajtur ende në memorie. Kushtëzimi if `num in cache` kthen `false`, dhe blloku else ekzekutohet: `Calculated! 20` printohet dhe vlera e rezultatit i shtohet objektit të cache-it. `cache` tani duket si `{ 10: 20 }`. + +Herën e dytë, objekti `cache` përmban vlerën që kthehet për `10`. Kushtëzimi if `num in cache` kthen `true`, dhe `'From cache! 20'` printohet. + +Herën e tretë, ne kalojmë `5 * 2` te funksioni i cili llogaritet si `10`. Objekti `cache` përmban vlerën që kthehet për `10`. Kushtëzimi if `num in cache` kthen `true`, dhe `'From cache! 20' printohet. + +

+
+ +--- + +###### 79. Cila është vlera e saj? + +```javascript +const myLifeSummedUp = ['☕', '💻', '🍷', '🍫']; + +for (let item in myLifeSummedUp) { + console.log(item); +} + +for (let item of myLifeSummedUp) { + console.log(item); +} +``` + +- A: `0` `1` `2` `3` dhe `"☕"` `"💻"` `"🍷"` `"🍫"` +- B: `"☕"` `"💻"` `"🍷"` `"🍫"` dhe `"☕"` `"💻"` `"🍷"` `"🍫"` +- C: `"☕"` `"💻"` `"🍷"` `"🍫"` dhe `0` `1` `2` `3` +- D: `0` `1` `2` `3` dhe `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
Përgjigja +

+ +#### Përgjigja: A + +Me unazën _for-in_, ne mund të iterojmë në vetitë _e numërueshme_. Në një array, vetitë e numërueshmë janë "çelësat" e elementeve të array, të cilët janë në të vërtetë indekset e tij. Mund të shikoni array si: + +`{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +Ku çelësat janë vetitë e numërueshme. `0` `1` `2` `3` printohet. + +Me unazën _for-of_, ne mund të iterojmë mbi __iterables__. Një array është një "iterable". Kur iterojmë mbi array, variabla "item" është e barabartë me elementin mbi të cilin po iterojmë aktualisht, "☕"` `"💻"` `"🍷"` `"🍫"` printohet. + +

+
+ +--- + +###### 80. Cila është vlera e saj? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2]; +console.log(list); +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
Përgjigja +

+ +#### Përgjigja: C + +Elementet e array mund të mbajnë çfarë vlere. Numra, stringje, objekte, array të tjerë, null, vlera boolean-e, undefined, dhe shprehje të tjera si data, funksione dhe kalkulime. + +Elementi do të jetë i barabartë me vlerën e kthyer. `1 + 2` kthen `3`, `1 * 2` kthen `2` dhe `1 / 2` kthen `0.5`. + +

+
+ +--- + +###### 81. Cila është vlera e saj? + +```javascript +function sayHi(name) { + return `Hi there, ${name}`; +} + +console.log(sayHi()); +``` + +- A: `Hi there,` +- B: `Hi there, undefined` +- C: `Hi there, null` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Paraprakisht, argumentet kane vlerën `undefined`, përveç në qoftëse ndonjë vlerë i kalohet në funksion. Në këtë rast, ne nuk e kaluam ndonjë vlerë për argumentin `name`. `name` është e barabartë me `undefined` e cila edhe printohet. + +Në ES6, ne mund të mbishkruajmë këtë vlerë paraprake `undefined` me parametër të definuar paraprakisht. Për shembull: + +`function sayHi(name = "Lydia") { ... }` + +Në këtë rast, nëse ne nuk kalojmë ndonjë vlerë ose e kalojmë `undefined`, `name` do të ishte gjithmonë i barabartë me stringun `Lydia`. + +

+
+ +--- + +###### 82. Cila është vlera e saj? + +```javascript +var status = '😎'; + +setTimeout(() => { + const status = '😍'; + + const data = { + status: '🥑', + getStatus() { + return this.status; + }, + }; + + console.log(data.getStatus()); + console.log(data.getStatus.call(this)); +}, 0); +``` + +- A: `"🥑"` and `"😍"` +- B: `"🥑"` and `"😎"` +- C: `"😍"` and `"😎"` +- D: `"😎"` and `"😎"` + +
Përgjigja +

+ +#### Përgjigja: B + +Vlera e fjalës kyçe `this` varet nga vendi ku e përdorni. Në një __metodë__, si metoda `getStatus`, fjala kyçe `this` i referohet _objektit që i përket metoda_. Metoda i përket objektit `data`, kështu që `this` i referohet objektit `data`. Kur printojmë `this.status`, vetia `status` në objektin `data` printohet, që është `"🥑"`. + +Me metodën `call`, ne mund të ndryshojmë objektin të cilit i referohet fjala kyçe `this`. Në __funksione__, fjala kyçe `this` i referohet _objektit të cilit i përket funksioni_. Ne deklaruam funksionin `setTimeout` në objektin _global_, kështu që brenda funksionit `setTimeout`, fjala kyçe `this` i referohet objektit _global_. Në objektin global, ekziston një variabël e quajtur _status_ me vlerën `"😎"`. Kur printoni `this.status`, `"😎"` printohet. + +

+
+ +--- + +###### 83. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +let city = person.city; +city = 'Amsterdam'; + +console.log(person); +``` + +- A: `{ name: "Lydia", age: 21 }` +- B: `{ name: "Lydia", age: 21, city: "Amsterdam" }` +- C: `{ name: "Lydia", age: 21, city: undefined }` +- D: `"Amsterdam"` + +
Përgjigja +

+ +#### Përgjigja: A + +0Vendosëm variablën `city` të barabartë me vlerën e vetisë të quajtur `city` në objektin `person.`. Në objekt nuk ka ndonjë veti e cila quhet `city`, kështu që variabla `city` ka vlerën `undefined`. + +Vini re, ne _nuk_ jemi duke iu referuar objektit `person`! Ne vetëm e vendosëm variablën `city` të barabartë me vlerën aktuale të vetisë `city` në objektin `person`. + +Pastaj, ne vendosëm `city` të barabartë me stringun `"Amsterdam"`. Kjo nuk e ndryshon objektin person: nuk ka ndonjë referencë tek ai objekt. + +Kur printojmë objektin `person`. objekti i pamodifikuar kthehet. + +

+
+ +--- + +###### 84. Cila është vlera e saj? + +```javascript +function checkAge(age) { + if (age < 18) { + const message = "Sorry, you're too young."; + } else { + const message = "Yay! You're old enough!"; + } + + return message; +} + +console.log(checkAge(21)); +``` + +- A: `"Sorry, you're too young."` +- B: `"Yay! You're old enough!"` +- C: `ReferenceError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Variablat e deklaruara me fjalët kyçe `const` dhe `let` janë të qasshme vetëm në bllokun ku shtrihen (_block-scoped_). Një bllok quhet gjithçka që gjendet brenda kllapave gjarpërore (`{ }`). Në këtë rast, kllapat gjarpërore e deklarimeve if/else. Nuk mund të i referencohemi një variable jashtë bllokut ku është deklaruar, sepse do të ngrihet ReferenceError. + +

+
+ +--- + +###### 85. Çfarë lloj informacioni do të printohet? + +```javascript +fetch('https://www.website.com/api/user/1') + .then(res => res.json()) + .then(res => console.log(res)); +``` + +- A: Rezultati i metodës `fetch`. +- B: Rezultati i thirrjes së dytë së metodës `fetch`. +- C: Rezultati i callback paraprak `.then()` +- D: Do të jetë gjithmonë undefined. + +
Përgjigja +

+ +#### Përgjigja: C + +Vlera e `res` në `.then` të dytë do të jetë e barabartë me vlerën e kthyer në `.then` paraprak. You mund të bëni `.then`-ë të tjerë si në shembull, ku vlera do të kalohet në trajtuesin tjetër. + +

+
+ +--- + +###### 86. Cili opsion do të mundësojë që të vendosim `hasName` të barabartë me `true`, nuk mund të kaloni si argument vlerën `true`? + +```javascript +function getName(name) { + const hasName = // +} +``` + +- A: `!!name` +- B: `name` +- C: `new Boolean(name)` +- D: `name.length` + +
Përgjigja +

+ +#### Përgjigja: A + +Me `!!name`, ne vendosim në qoftëse vlera e `name` është e vërtetë osë false. Nëse "name" është e vërtetë, për të cilën duam të testojmë, `!name` kthen `false`. `!false` (e cila është vlera të cilën `!!name` ka) kthen `true`. + +Kur vendosim `hasName` të barabartë me `name`, ju vendosni `hasName` të barabartë me çdo vlerë të cilën e kaloni si arguemnt tek funksioni `getName`, jo vlera boolean-e `true`. + +`new Boolean(true)` kthen një mbështjellës së objektit, jo vetë vlerën boolean-e. + +`name.length` kthen gjatësinë e argumentit të kaluar, jo në qoftëse është `true` ose jo. + +

+
+ +--- + +###### 87. Cila është vlera e saj? + +```javascript +console.log('I want pizza'[0]); +``` + +- A: `"""` +- B: `"I"` +- C: `SyntaxError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Në mënyrë që të marrim karakterin në një indeks specifik në string, mund të përdorimin notacionin e kllapave të mëdha "[]". Karakteri i parë në string ka indeksin 0, dhe kështu me rradhë. Në këtë rast, ne duam të marrim elementin me indeks 0, karakterin `"I"`, i cili printohet. + +Vini re se kjo metodë nuk suportohet në IE7 e më poshtë. Në këtë rast përdorni `.charAt()`. + +

+
+ +--- + +###### 88. Cila është vlera e saj? + +```javascript +function sum(num1, num2 = num1) { + console.log(num1 + num2); +} + +sum(10); +``` + +- A: `NaN` +- B: `20` +- C: `ReferenceError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne mund të përcaktojmë një vlerë paraprakisht të barabartë me ndonjë parametër tjetër të funksionit, përderisa ato janë të deinuara përpara vlerës së paradefinuar. Ne e kalojmë vlerën `10` tek funksioni `sum`. Nëse funksioni `sum` pranon vetëm një argument, do të thotë se vlera për `num2` nuk është kaluar, dhe vlera e `num1` është e barabartë me vlerën `10` e cila ka kaluar si argument në këtë rast. Vlera e paradefinuar e `num2` është vlera e `num1`, e cila është `10`. `num1 + num2` kthen `20`. + +Në qoftëse provoni të vendosni një vlerë të paradefinuar të barabartë me një parametër i cili definohet _pastaj_ (në të djathë), vlera e parametrit nuk do të jetë e inicializuar ende, e cila do të kthejë një error. + +

+
+ +--- + +###### 89. Cila është vlera e saj? + +```javascript +// module.js +export default () => 'Hello world'; +export const name = 'Lydia'; + +// index.js +import * as data from './module'; + +console.log(data); +``` + +- A: `{ default: function default(), name: "Lydia" }` +- B: `{ default: function default() }` +- C: `{ default: "Hello world", name: "Lydia" }` +- D: Global object of `module.js` + +
Përgjigja +

+ +#### Përgjigja: A + +Me sintaksën `import * as name`, ne importojmë _të gjithë eksportet_ nga fajlli `module.js` në `index.js` si një objekt i ri i cili quhet `data` i cili krijohet. Në `module.js`, gjenden dy eksporta: eksporti i paracaktuar dhe një eksport i emërtuar. Eksporti i paracaktuar është funksion i cili kthen stringun `Hello World`, dhe esksporti i emëruar është variabla e quajtur `name` e cila ka vlerën e stringut `"Lydia"`. + +Objekti `data` ka një veti `default` për eksportin e paracaktuar, vetitë e tjera kanë emrat e eksporteve të emëruara dhe vlerat e tyre korrespoduese. + +

+
+ +--- + +###### 90. Cila është vlera e saj? + +```javascript +class Person { + constructor(name) { + this.name = name; + } +} + +const member = new Person('John'); +console.log(typeof member); +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
Përgjigja +

+ +#### Përgjigja: C + +Klasat janë si sintaksë që është krijuar për t'i bërë gjërat më të lehta për t'u lexuar ose për t'u shprehur për funksionet e konstruktorëve. Ekuivante e klasës `Person` si funksion kontruktorë do të ishte: + +```javascript +function Person(name) { + this.name = name; +} +``` + +Thirrja e një konstruktori me `new` rezulton në krijimin e një instance të `Person`, `typeof` do të kthejë `"object"` për një instancë. `typeof member` kthen `"object"`. + +

+
+ +--- + +###### 91. Cila është vlera e saj? + +```javascript +let newList = [1, 2, 3].push(4); + +console.log(newList.push(5)); +``` + +- A: `[1, 2, 3, 4, 5]` +- B: `[1, 2, 3, 5]` +- C: `[1, 2, 3, 4]` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `.push` kthen _gjatësinë e re_ të array, jo vetë array! Duke vendosur `newList` të barabartë me `[1, 2, 3].push(4)`, e vendosim `newList` të barabartë me gjatësinë e re të array: `4`. + +Pastaj, ne provojmë të përdorim metodën `.push` në `newList`. Meqenëse `newList` është vlera numerike e `4` ne nuk mund të përdorim metodën `.push`: do të ngrihet TypeError. + +

+
+ +--- + +###### 92. Cila është vlera e saj? + +```javascript +function giveLydiaPizza() { + return 'Here is pizza!'; +} + +const giveLydiaChocolate = () => + "Here's chocolate... now go hit the gym already."; + +console.log(giveLydiaPizza.prototype); +console.log(giveLydiaChocolate.prototype); +``` + +- A: `{ constructor: ...}` `{ constructor: ...}` +- B: `{}` `{ constructor: ...}` +- C: `{ constructor: ...}` `{}` +- D: `{ constructor: ...}` `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +Funskionet e rregullta, të tillë si funksioni `giveLydiaPizza`, kanë vetinë `prototype`, e cila është një objekt (veti e objektit) me veti `constructor`. Funksionet shigjetë (arrow functions) sidoqoftë, të tilla si funskioni `giveLydiaChocolate`, nuk e kanë këtë veti `prototype`. Kur tentojmë të i qasemi vetisë `prototype` duke pëdorur `giveLydiaChocolate.prototype` do të na kthehet `undefined`. + +

+
+ +--- + +###### 93. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const [x, y] of Object.entries(person)) { + console.log(x, y); +} +``` + +- A: `name` `Lydia` and `age` `21` +- B: `["name", "Lydia"]` and `["age", 21]` +- C: `["name", "age"]` and `undefined` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: A + +`Object.entries(person)` kthen një array me array të ndërthurur, i cili përmban çelësat dhe objektet: + +`[ [ 'name', 'Lydia' ], [ 'age', 21 ] ]` + +Përdorimi i unazës `for-of`, na mundëson iterimin në secilin element në array, dhe nën array në këtë rast. Ne mund të destrukturojmë nën array menjëherë në unazën for-of, duke përdorur `const [x, y]`. `x` është e barabartë me elementin e parë në nën array, `y` është e barabartë me elementin e dytë në nën array. + +Nën array i parë është `["name", "Lydia"]`, me `x` të barabartë me `"name"`, dhe `y` të barabartë me `"Lydia"`, e cila printohet. Nën array i dytë është `["age", 21 ]`, me `x` të barabartë me `"age"`, dhe `y` të barabartë me `21`, e cila printohet. + +

+
+ +--- + +###### 94. Cila është vlera e saj? + +```javascript +function getItems(fruitList, ...args, favoriteFruit) { + return [...fruitList, ...args, favoriteFruit] +} + +getItems(["banana", "apple"], "pear", "orange") +``` + +- A: `["banana", "apple", "pear", "orange"]` +- B: `[["banana", "apple"], "pear", "orange"]` +- C: `["banana", "apple", ["pear"], "orange"]` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: D + +`...args` është "rest" parametër. Vlera e "rest" parametrit është një array i cili përmban të gjitha argumentet e mbetura, **dhe mund të jetë vetëm parametri i fundit**! Në këtë shembull, "rest" parametri ishte parametri i dytë. Kjo nuk është e mundur, dhe do të ngrisë gabim sintaksorë. + +```javascript +function getItems(fruitList, favoriteFruit, ...args) { + return [...fruitList, ...args, favoriteFruit]; +} + +getItems(['banana', 'apple'], 'pear', 'orange'); +``` + +Shembulli i mësipërm funskionon. Do të kthejë array `[ 'banana', 'apple', 'orange', 'pear' ]` + +

+
+ +--- + +###### 95. Cila është vlera e saj? + +```javascript +function nums(a, b) { + if (a > b) console.log('a is bigger'); + else console.log('b is bigger'); + return + a + b; +} + +console.log(nums(4, 2)); +console.log(nums(1, 2)); +``` + +- A: `a is bigger`, `6` dhe `b is bigger`, `3` +- B: `a is bigger`, `undefined` dhe `b is bigger`, `undefined` +- C: `undefined` dhe `undefined` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Në JavaScript, nuk e duhet të e shkruajmë pikëpresjen `;` në mënyrë eksplicite, sidoqoftë makina e JavaScript prapë i vendos ato pas deklarimeve. Kjo quhet __Automatic Semicolon Insertion__ (vendosja e pikëpresjes automatikisht). Një deklaratë për shembull mund të jetë variabla, ose fjalët kyçe si `throw`, `return`, `break` etj. + +Në këtë rast, ne shkruajtëm deklaratën `return`, dhe vlerën tjetër `a + b` në rresht të ri. Sidoqoftë, meqenëse është rresht i ri, makina nuk e di se në të vërtetë ajo është vlera që ne po dëshirojmë të kthejmë. Në vend se të e llogarisë në atë mënyrë, në mënyrë automatike vendoset `return`. Kjo mund të shikohet edhe si kjo sintaksë: + +```javascript +return; +a + b; +``` + +Kjo do të thotë se `a + b` nuk arrihet asnjëherë, meqenëse funksioni ndalon ekzekutimin pas fjalës kyçe `return`. Nëse asnjë vlerë nuk kthehet si në këtë rast, funksioni kthen `undefined`. Vini re se nuk ka ndonjë përfshirje automatike pas deklarimit `if/else` + +

+
+ +--- + +###### 96. Cila është vlera e saj? + +```javascript +class Person { + constructor() { + this.name = 'Lydia'; + } +} + +Person = class AnotherPerson { + constructor() { + this.name = 'Sarah'; + } +}; + +const member = new Person(); +console.log(member.name); +``` + +- A: `"Lydia"` +- B: `"Sarah"` +- C: `Error: cannot redeclare Person` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne mund të iu shoqërojmë klasave konstruktorët e tjerë të klasave/funksioneve. Në këtë rast, ne vendosim `Person` të barabartë me `AnotherPerson`. Emri në këtë konstruktor është `Sarah`, kështu që vetia e emrit në instancën e re `Person`, `member` është `“Sarah”`. + +

+
+ +--- + +###### 97. Cila është vlera e saj? + +```javascript +const info = { + [Symbol('a')]: 'b', +}; + +console.log(info); +console.log(Object.keys(info)); +``` + +- A: `{Symbol('a'): 'b'}` dhe `["{Symbol('a')"]` +- B: `{}` dhe `[]` +- C: `{ a: "b" }` dhe `["a"]` +- D: `{Symbol('a'): 'b'}` dhe `[]` + +
Përgjigja +

+ +#### Përgjigja: D + +Një Symbol nuk është i _numërueshëm_. Metoda Object.keys kthen të gjithë çelësat e _numërueshëm në një objekt. Symbol nuk do të jetë i dukshëm, dhe një array i zbrazët do të kthehet. Kur e printojmë objektin në tërësi, të gjitha vetitë janë të dukshme, edhe ato të cilat nuk janë te numërueshme. + +Kjo është vetëm një nga shumë vetitë e symbol, përveç përfaqësimit të një vlere krejtësisht unike (e cila parandalon konflikt në emërtim të objekteve, për shembull kur punoni me 2 librari që duan të shtojnë vetitë në të njëjtin objekt), ju gjithashtu mund të "fshehni" vetitë e objekteve në këtë mënyrë (edhe pse jo plotësisht. Ju mund t'i qaseni simboleve duke përdorur metodën `Object.getOwnPropertySymbols()`). + +

+
+ +--- + +###### 98. Cila është vlera e saj? + +```javascript +const getList = ([x, ...y]) => [x, y] +const getUser = user => { name: user.name, age: user.age } + +const list = [1, 2, 3, 4] +const user = { name: "Lydia", age: 21 } + +console.log(getList(list)) +console.log(getUser(user)) +``` + +- A: `[1, [2, 3, 4]]` and `SyntaxError` +- B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` +- C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` +- D: `Error` and `{ name: "Lydia", age: 21 }` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `getList` merr një array si argument. Brenda kllapave të funksionit `getList`, ne e destrukturojmë ketë array në mënyrën e duhur. Kjo mund të shihet edhe si: + +`[x, ...y] = [1, 2, 3, 4]` + +Me "rest" parametrin `...y`, ne i vendosim argumentet "e mbetura" në një array. Argumentet e mbetura janë `2`, `3` dhe `4` në këtë rast. Vlera e `y` është një array, i cili i përmban të gjithë parametrat e mbetur. Vlera e `x` është e barabartë me `1` në këtë rast kur e printojmë `[x, y]`, printohet `[1, [2, 3, 4]]`. + +Funskioni `getUser` merr një objekt. Me funksionet shigjetë (arrow function), ne nuk kemi nevojë të shkruajmë kllapat gjarpërore nëse vetëm dëshirojmë të kthejmë një vlerë. Sidoqoftë, nëse dëshironi që në mënyrë instante të ktheni një objekt nga një arrow funksion, mund të e shkruani brenda kllapave të vogla "()", përndryshe çdo gjë mes dy kllapave do të interpretohet si një deklaratë blloku. Në këtë rast kodi në mes të kllapave nuk është kod valid i JavaScript, kështu që do të ngrihet `SyntaxError`. + +Funskioni i meposhtëm do të kthente një objekt: + +`const getUser = user => ({ name: user.name, age: user.age })` + +

+
+ +--- + +###### 99. Cila është vlera e saj? + +```javascript +const name = 'Lydia'; + +console.log(name()); +``` + +- A: `SyntaxError` +- B: `ReferenceError` +- C: `TypeError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Variabla `name` mban vlerën e një stringu, i cili nuk është funksion, prandaj nuk mund të thirret si i tillë. + +TypeErrors do të ngrihen kur një vlerë nuk është e tipit që pritet. JavaScript pret që `name` të jetë një funksion meqenëse po provojmë të e thirrim atë. Sidoqoftë është një string, prandaj do të marrim TypeError: "name" nuk është një funksion. + +SyntaxErrors do të ngrihen kur ne shënojmë diçka e cila nuk është valide në JavaScript, për shembull kur e shënojmë fjalën `return` si `retrun`. +ReferenceErrors ngrihen kur Javascript-i nuk është në gjendje të gjejë referencë tek një vlerë të cilën ne provojmë të i qasemi. + +

+
+ +--- + +###### 100. Cila është vlera në dalje? + +```javascript +// 🎉✨ Kjo është pytja jonë e 100! ✨🎉 + +const output = `${[] && 'Im'}possible! +You should${'' && `n't`} see a therapist after so much JavaScript lol`; +``` + +- A: `possible! You should see a therapist after so much JavaScript lol` +- B: `Impossible! You should see a therapist after so much JavaScript lol` +- C: `possible! You shouldn't see a therapist after so much JavaScript lol` +- D: `Impossible! You shouldn't see a therapist after so much JavaScript lol` + +
Përgjigja +

+ +#### Përgjigja: B + +`[]` është vlerë "truthy". Me operatorin `&&`, vlera në anën e djathtë do të kthehet nëse vlera në anën e majtë është vlerë "truthy". Në këtë rast, vlera në anën e majtë `[]` është vlerë "truthy" prandaj `"Im"` do të kthehet. + +`""` është vlerë "falsy". Nësë ana e majtë është falsy, asgjë nuk kthehet. `n't` nuk do të kthehet. + +

+
+ +--- + +###### 101. Cila është vlera në dalje? + +```javascript +const one = false || {} || null; +const two = null || false || ''; +const three = [] || 0 || true; + +console.log(one, two, three); +``` + +- A: `false` `null` `[]` +- B: `null` `""` `true` +- C: `{}` `""` `[]` +- D: `null` `null` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Me operatorin `||`, ne mund të kthejmë vlerën e parë "truthy" të operandit. Nëse të gjitha vlerat janë "falsy", operandi i fundit do të kthehet. + +`(false || {} || null)`: objekti i zbrazët `{}` është vlerë "truthy". Ky është i pari dhe i vetmi vlerë "truthy", i cili kthehet. `one` është i barabartë me `{}`. + +`(null || false || "")`: të gjithë operandët janë vlera "falsy". Kjo do të thotë se operandi i fundit, `""` do të kthehet. `two` është i barabartë me `""`. + +`([] || 0 || "")`: array i zbrazët `[]` është vlerë "truthy". Kjo është vlera e parë "truthy" e cila kthehet. `three` është e barabartë me `[]`. + +

+
+ +--- + +###### 102. Cila është vlera në dalje? + +```javascript +const myPromise = () => Promise.resolve('I have resolved!'); + +function firstFunction() { + myPromise().then(res => console.log(res)); + console.log('second'); +} + +async function secondFunction() { + console.log(await myPromise()); + console.log('second'); +} + +firstFunction(); +secondFunction(); +``` + +- A: `I have resolved!`, `second` and `I have resolved!`, `second` +- B: `second`, `I have resolved!` and `second`, `I have resolved!` +- C: `I have resolved!`, `second` and `second`, `I have resolved!` +- D: `second`, `I have resolved!` and `I have resolved!`, `second` + +
Përgjigja +

+ +#### Përgjigja: D + +Me një premtim, në thelb themi _Dëshiroj ta ekzekutoj këtë funksion, por do të e lë mënjanë për momentin ndërsa është duke u ekzekutuar pasi kjo mund të marrë pak kohë. Vetëm kur një vlerë e caktuar zgjidhet (ose refuzohet) dhe kur "call stack" është bosh, unë dua ta përdor këtë vlerë._ + +Ne mund të marrim këtë rezultat me të dy: `.then` dhe fjalën kyçe `await` në `async` funksione. Edhe pse mund të marrim vlerën e 'promise' me të dy `.then` dhe `await` ato funksionojnë pak më ndryshe. + +Në funksionin e parë `firstFunction`, në një mënyrë e vendosim funksionin 'myPromise' mënjanë përgjatë ekzekutimit, por ne e vazhdojmë ekzekutimin e kodit tjetër, i cili në këtë rast është `console.log('second')`. Pastaj, funksioni zgjidhet me stringun `I have resolved`, i cili pastaj printohet pasi që e sheh se call stack është i zbrazët. + +Me fjalën kyçe `secondFunction`, në të vërtetë e pauzojmë ekzekutimin e funksionit async derisa vlera të zgjidhet përpara se të vazhdojmë tek rreshti tjetër. + +Kjo do të thotë se pret për `myPromise` të zgjidhet me vlerën `I have resolved`, dhe pasi ajo të ndodhë ne vazhdojmë ne rreshtin e ardhshëm: `second` do të printohet. + +

+
+ +--- + +###### 103. Cila është vlera në dalje? + +```javascript +const set = new Set(); + +set.add(1); +set.add('Lydia'); +set.add({ name: 'Lydia' }); + +for (let item of set) { + console.log(item + 2); +} +``` + +- A: `3`, `NaN`, `NaN` +- B: `3`, `7`, `NaN` +- C: `3`, `Lydia2`, `[object Object]2` +- D: `"12"`, `Lydia2`, `[object Object]2` + +
Përgjigja +

+ +#### Përgjigja: C + +Operatori `+` nuk përdoret vetëm vetëm për të mbledhur vlerat numberike, por mund të e përdorim për bashkimin e stringjeve. Sa herë që makina e JavaScript e vëren se një ose më shumë vlera nuk janë numra, e shndërron numrin në string. + +Ne fillim është `1` i cili është vlerë numerike. `1 + 2` kthen numrin 3. + +Megjithatë, vlera e dytë është string `"Lydia"`. `"Lydia"` është string dhe `2` është numër: `2` shndërrohet në string. `"Lydia"` dhe `"2"` bashkohen, dhe kjo rezulton në stringun `"Lydia2"`. + +`{ name: "Lydia"}` është objekt. Nuk është as numër as objekt është string, prandaj i konsideron si stringje të dyja. Sa herë që i konsiderojmë si stringje objektet e zakonshme, behet `"[object Object"]`.`"[object Object"]` bashkohet me `"2"` dhe bëhet `"[object Object]2"`. + +

+
+ +--- + +###### 104. Cila është vlera e saj? + +```javascript +Promise.resolve(5); +``` + +- A: `5` +- B: `Promise {: 5}` +- C: `Promise {: 5}` +- D: `Error` + +
Përgjigja +

+ +#### Përgjigja: C + +Ne mund të kalojmë qfarëdo vlere që duam te `Promise.resolve`, 'promise' ose 'jo-promise'. Metoda vetë kthen një 'promise' e cila zgjidhet me vlerën (`fulfilled`). Nëse i kaloni një funksion të zakonshëm, do të zgjidhet një promise me një vlerë të zakonshme. Nëse i kaloni një 'promise' si argument, do të zgjidhjet një promise me vlerën e zgjidhur me vlerën që i kalohet si promise. + +Në këtë rast, ne vetëm i kaluam si argument vlerën numerike `5`. Kthen promise të zgjidhur me vlerë `5`. + +

+
+ +--- + +###### 105. Cila është vlera e saj? + +```javascript +function compareMembers(person1, person2 = person) { + if (person1 !== person2) { + console.log('Not the same!'); + } else { + console.log('They are the same!'); + } +} + +const person = { name: 'Lydia' }; + +compareMembers(person); +``` + +- A: `Not the same!` +- B: `They are the same!` +- C: `ReferenceError` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: B + +Objektet vendosen si argumente në bazë të referencës së tyre. Kur i kontrollojmë objektet me operatorin për barazim strikt (`===`), ne po kontorllojmë referencën e tyre. + +Ne e paracaktuam vlerën e `person2` të barabartë me objektin `person`, dhe e kaluam objektin `person` si vlerë të `person1`. + +Kjo do të thotë që të dy vlerat kanë referencë të e njejta hapësirë memorike, dhe kështu ato janë të barabarta. + +Blloku i kodit në deklarimin `else` ekzekutohet dhe `They are the same!` printohet. + +

+
+ +--- + +###### 106. Cila është vlera e saj? + +```javascript +const colorConfig = { + red: true, + blue: false, + green: true, + black: true, + yellow: false, +}; + +const colors = ['pink', 'red', 'blue']; + +console.log(colorConfig.colors[1]); +``` + +- A: `true` +- B: `false` +- C: `undefined` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: D + +Në JavaScript, kemi dy mënyra për të iu qasur vetive të një objekti: notacioni me kllapa të mëdha "[]" ose notacioni me pikë ".". Në këtë shembull ne po e perdorim notacionin (`colorConfig.colors`) në vend të notacionit me kllapë (`colorConfig["colors"]`). + +Me notacionin me pikë, JavaScript provon të gjejë veti në objekt me saktësisht të njejtin emër. Në këtë shembull, JavaScript provon të gjejë një veti e cila quhet `colors` në objektin `colorConfig`. Nuk ka ndonjë veti të quajtur `colors`, prandaj kjo do të kthejë `undefined`. Pastaj ne provojmë të i qasemi vlerës së elementit të parë ne array duke përdorur `[1]`. Nuk mund të e bëjmë këtë në vlerën e cila është `undefined`, prandaj do të ngrihet `TypeError`: `Cannot read property '1' of undefined`. + +JavaScript i interpreton deklarimet. Kur përdorim notacionin me kllapa të mëdha, e sheh kllapën hapëse `[` dhe vazhdon kërkon derisa të gjen kllapën mbyllëse `]`. Vetëm atëherë, e llogarit deklarimin. Nëse do të përdornim `colorConfig[colors[1]]`, do të kishte kthyer vlerën e vetisë `red` në objektin `colorConfig`. + +

+
+ +--- + +###### 107. Cila është vlera e saj? + +```javascript +console.log('❤️' === '❤️'); +``` + +- A: `true` +- B: `false` + +
Përgjigja +

+ +#### Përgjigja: A + +Në prapavijë, emoji-t janë kode të veçanta. Unikodet për emoji-t e zemrës janë `"U+2764 U+FE0F"`. Këto janë gjithmonë të njëjta për të njëjtat emoji, kështu që ne po krahasojmë dy stringje të barabarta me njëri-tjetrin, gjë që ktheh 'e vërtetë'. + +

+
+ +--- + +###### 108. Cila nga këto metoda e modifikon array origjinal? + +```javascript +const emojis = ['✨', '🥑', '😍']; + +emojis.map(x => x + '✨'); +emojis.filter(x => x !== '🥑'); +emojis.find(x => x !== '🥑'); +emojis.reduce((acc, cur) => acc + '✨'); +emojis.slice(1, 2, '✨'); +emojis.splice(1, 2, '✨'); +``` + +- A: `All of them` +- B: `map` `reduce` `slice` `splice` +- C: `map` `slice` `splice` +- D: `splice` + +
Përgjigja +

+ +#### Përgjigja: D + +Me motodën `splice`, ne modifikojmë array origjinal duke fshirë, zëvendësuar ose shtuar elemente. Në këtë rast, ne larguam 2 gjëra duke filluar nga indeksi 1 ( larguam `'🥑'` dhe `'😍'`) dhe shtuam ✨ në vend të tyre. + +`map`, `filter` dhe `slide` kthen array të ri, `find` kthen një element dhe `reduce` kthen një vlerë të reduktuar. + +

+
+ +--- + +###### 109. Cila është vlera e saj? + +```javascript +const food = ['🍕', '🍫', '🥑', '🍔']; +const info = { favoriteFood: food[0] }; + +info.favoriteFood = '🍝'; + +console.log(food); +``` + +- A: `['🍕', '🍫', '🥑', '🍔']` +- B: `['🍝', '🍫', '🥑', '🍔']` +- C: `['🍝', '🍕', '🍫', '🥑', '🍔']` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne vendosëm vlerën e vetisë `favoriteFood` në objektin `info` të barabartë me stringun me emoji-n e picës, `'🍕'`. Një string është një tip i të dhënave primitive. Në JavaScript, tipet primitive të të dhënave nuk ndërveprojnë me referencë. + +Në JavaScript, tipet primitive të të dhënave (gjithçka që nuk është objekt) ndërveprojnë me _vlerë_. Në këtë rast, ne vendosim vlerën e vetisë `favoriteFood` në objektin `info` të barabartë me vlerën e elementit të parë në array `food`, stringu me emoji-n e picës në këtë rast (`'🍕'`). Një string është një tip i të dhënave primitive dhe ndërvepron sipas vlerës (shikoni [blogpost](https://www.theavocoder.com/complete-javascript/2018/12/21/by-value-vs-by-reference) nëse jeni të interesuar të mësoni më shumë) + +Më pas, ne ndryshojmë vlerën e vetisë `favoriteFood` në objektin `info`. Vargu `food` nuk ka ndryshuar, pasi vlera e `favoriteFood` ishte thjesht një _kopje_ e vlerës së elementit të parë në grup dhe nuk ka një referencë për të njëjtin vend në memorie si elementi në `food[0]`. Kur printojmë 'food', është ende array origjinal, "['🍕", "🍫", "🥑", "🍔"]". + +

+
+ +--- + +###### 110. Çfarë bën kjo metodë? + +```javascript +JSON.parse(); +``` + +- A: Parson JSON në një vlerë të JavaScript. +- B: Parson një objekt të JavaScript në JSON. +- C: Parson çfarëdo vlere të JavaScript në JSON. +- D: Parson JSON vetëm në objekt të JavaScript + +
Përgjigja +

+ +#### Përgjigja: A + +Me metodën `JSON.parse()`, ne mund të parsojmë JSON stringun në një vlerë JavaScript-i. + +```javascript +// Stringifimi i një numri në një JSON valid, pastaj parsimi i nje4 stringu në vlerë të JavaScript: +const jsonNumber = JSON.stringify(4); // '4' +JSON.parse(jsonNumber); // 4 + +// Stringifimi i një array në JSON valid, pastaj parsimi i JSON stringut ne një vlerë të JavaScript: +const jsonArray = JSON.stringify([1, 2, 3]); // '[1, 2, 3]' +JSON.parse(jsonArray); // [1, 2, 3] + +// Stringifimi i një objekti në JSON valid, pastaj parsimi i JSON stringut në një vlerë të JavaScript: +const jsonArray = JSON.stringify({ name: 'Lydia' }); // '{"name":"Lydia"}' +JSON.parse(jsonArray); // { name: 'Lydia' } +``` + +

+
+ +--- + +###### 111. Cila është vlera e saj? + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); + let name = 'Sarah'; +} + +getName(); +``` + +- A: Lydia +- B: Sarah +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Secili funksion ka _kontekstin e vetë të ekzekutimit_. Funksioni `getName` së pari shikon brenda kontekstit të tij në qoftëse përmban variablën `name` të cilën po provojmë të i qasemi. Në këtë rast, funksioni `getName` përmban variablën e tij `name`: e deklaruam variablën `name` me fjalën kyçe `let`m dhe i inicializuam vlerën `'Sarah'`. + +Variablat me fjalën kyçe `let` (dhe `const`) ngriten (hoistoh-en), por për dallim nga `var` nuk inicializohen. Ato nuk janë të qasshme më herët se rreshti në të cilin janë deklaruar (i kemi deklaruar). Kjo quhet "zona e vdekur e përkohshme" (temporal dead zone). Kur tentojmë të i qasemi variablave përpara se ato të deklarohen, JavaScript hedh `ReferenceError`. + +Nëse nuk do të kishim deklaruar `name` brenda funksionit `getName`, makina e JavaScript do të kishte shikuar poshtë _zingjirit të shtrirjes_. Fusha e jashtme ka variabël të quajtur `name` me vlerë `Lydia`. Në këtë rast, do të kishte printuat `Lydia`. + +```javascript +let name = 'Lydia'; + +function getName() { + console.log(name); +} + +getName(); // Lydia +``` + +

+
+ +--- + +###### 112. Cila është vlera e saj? + +```javascript +function* generatorOne() { + yield ['a', 'b', 'c']; +} + +function* generatorTwo() { + yield* ['a', 'b', 'c']; +} + +const one = generatorOne(); +const two = generatorTwo(); + +console.log(one.next().value); +console.log(two.next().value); +``` + +- A: `a` dhe `a` +- B: `a` dhe `undefined` +- C: `['a', 'b', 'c']` dhe `a` +- D: `a` dhe `['a', 'b', 'c']` + +
Përgjigja +

+ +#### Përgjigja: C + +Me fjalën kyçe `yield`, ne i japim vlerat në një funksion gjenerator. Me fjalën kyçe `yield*`, ne mund të nxjerrim vlera nga një funksion tjetër gjenerues, ose objekt i iterueshëm (për shembull një array). + +Në `generatorOne`, ne japim të gjithë array `['a', 'b', 'c']'` duke përdorur fjalën kyçe `yield`. Vlera e vetisë `value` në objektin e kthyer me metodën `next` në `one` (`one.next().value`) është e barabartë me të gjithë grupin `['a', 'b', 'c']`. + +```javascript +console.log(one.next().value); // ['a', 'b', 'c'] +console.log(one.next().value); // undefined +``` + +Në `generatorTwo`, ne përdorim fjalën kyçe `yield*`. Kjo do të thotë se vlera e parë e dhënë e `two`, është e barabartë me vlerën e dhënë në iterimin e parë. Iteratori është grupi `['a', 'b', 'c']`. Vlera e parë e dhënë është `a`, kështu që herën e parë që thërrasim `two.next().value`, kthehet `a`. + +```javascript +console.log(two.next().value); // 'a' +console.log(two.next().value); // 'b' +console.log(two.next().value); // 'c' +console.log(two.next().value); // undefined +``` + +

+
+ +--- + +###### 113. Cila është vlera e saj? + +```javascript +console.log(`${(x => x)('I love')} to program`); +``` + +- A: `I love to program` +- B: `undefined to program` +- C: `${(x => x)('I love') to program` +- D: `TypeError` + +
Përgjigja +

+ +#### Përgjigja: A + +Shprehjet brenda shablloneve literale vlerësohen së pari. Kjo do të thotë që stringu do të përmbajë vlerën e kthyer të shprehjes, funksionin e thirrur menjëherë `(x => x)('I love')` në këtë rast. Ne e kalojmë vlerën `'I love'` si argument në funksionin e shigjetës `x => x`. `x` është e barabartë me `'I love'`, e cila kthehet. Kjo rezulton në `I love to program`. + +

+
+ +--- + +###### 114. Çfarë do të ndodhë? + +```javascript +let config = { + alert: setInterval(() => { + console.log('Alert!'); + }, 1000), +}; + +config = null; +``` + +- A: Callback `setInterval` nuk do të thirret. +- B: Callback `setInterval` do të thirret një herë. +- C: Callback `setInterval` do të thirret çdo sekond. +- D: Nuk e kemi thirrur asnjëherë `config.alert()`, config është `null`. + +
Përgjigja +

+ +#### Përgjigja: C + +Zakonisht kur i vendosim objektet të barabarta me `null`, ato objekte mirren nga _garbage collector_ pasi nuk ka më referencë për ato objekte. Megjithatë, meqenëse funksioni callback brenda `setInterval` është një funksion me shigjetë (pra i lidhur me objektin `config`), funksioni callback ende mban një referencë për objektin `config`. +Për sa kohë ka një referencë, objekti nuk do të merret nga 'garbage collector' (menaxhuesi i memories për të u larguar). +Meqenëse ky është një interval, vendosja e `config` në '`null` ose `delete` `config.alert` nuk do të mbledhet nga garbage-collector për intervalin, kështu që intervali do të vazhdojë të thirret. +Për ta hequr nga memoria duhet të e pastrojmë me `clearInterval(config.alert)`. +Meqenëse nuk u fshi, funksioni `setInterval` callback do të vazhdojë të thirret çdo 1000ms (1s). + +

+
+ +--- + +###### 115. Cila metodë do të kthejë vlerën `'Hello world!'`? + +```javascript +const myMap = new Map(); +const myFunc = () => 'greeting'; + +myMap.set(myFunc, 'Hello world!'); + +//1 +myMap.get('greeting'); +//2 +myMap.get(myFunc); +//3 +myMap.get(() => 'greeting'); +``` + +- A: 1 +- B: 2 +- C: 2 dhe 3 +- D: Të gjitha + +
Përgjigja +

+ +#### Përgjigja: B + +Kur shtoni një çift çelës/vlerë duke përdorur metodën `set`, çelësi do të jetë vlera e argumentit të parë që i kalohet funksionit `set`, dhe vlera do të jetë argumenti i dytë që i kalohet funksionit `set`. Çelësi është _functioni_ `() => 'greeting'` në këtë rast, dhe vlera `'Hello world'`. `myMap` tani është `{ () => 'greeting' => 'Hello world!' }`. + +1 është gabim, pasi çelësi nuk është `'greeting'` por `() => 'greeting'`. +3 është gabim, pasi ne po krijojmë një funksion të ri duke e kaluar atë si parametër në metodën `get`. Objekti ndërvepron me _referencë_. Funksionet janë objekte, prandaj dy funksione nuk janë kurrë rreptësisht të barabarta, edhe nëse janë identike: ato kanë një referencë në një vend të ndryshëm në memorie. + +

+
+ +--- + +###### 116. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +const changeAge = (x = { ...person }) => (x.age += 1); +const changeAgeAndName = (x = { ...person }) => { + x.age += 1; + x.name = 'Sarah'; +}; + +changeAge(person); +changeAgeAndName(); + +console.log(person); +``` + +- A: `{name: "Sarah", age: 22}` +- B: `{name: "Sarah", age: 23}` +- C: `{name: "Lydia", age: 22}` +- D: `{name: "Lydia", age: 23}` + +
Përgjigja +

+ +#### Përgjigja: C + +Të dy funksionet `changeAge` dhe `changeAgeAndName` kanë një parametër të paracaktuar, përkatësisht një objekt të krijuar rishtazi `{...person}`. Ky objekt ka kopje të të gjithë çelësave/vlerave në objektin `person`. + +Së pari, e thirrim funksionin `changeAge` dhe e kalojmë objektin `person` si argument. Ky funksion rrit vlerën e vetisë `age` për 1. `person` tani është `{ name: "Lydia", age: 22 }`. + +Pastaj, e thirrim funksionin `changeAgeAndName`, sidoqoftë ne nuk e kalojmë një parametër. Në vend të kësaj, vlera e `x` është e barabartë me objektin e ri `{ ...person }`. Meqenëse është një objekt i ri, nuk do të afektojë vlerën e vetive në objektin `person`. `person` ende është e barabartë me `{ name: "Lydia", age: 22 }`. + +

+
+ +--- + +###### 117. Cili nga funksionet e mëposhtme do të kthejë `6`? + +```javascript +function sumValues(x, y, z) { + return x + y + z; +} +``` + +- A: `sumValues([...1, 2, 3])` +- B: `sumValues([...[1, 2, 3]])` +- C: `sumValues(...[1, 2, 3])` +- D: `sumValues([1, 2, 3])` + +
Përgjigja +

+ +#### Përgjigja: C + +Me operatorin spread `...`, me mund të _përhapim_ iteruesit në elemente individuale. Funksioni `sumValues` merr tre argumente: `x`, `y` dhe `z`. `...[1, 2, 3]` do të rezultojë në `1, 2, 3`, të cilin ia kalojmë funksionit `sumValues`. + +

+
+ +--- + +###### 118. Cila është vlera e saj? + +```javascript +let num = 1; +const list = ['🥳', '🤠', '🥰', '🤪']; + +console.log(list[(num += 1)]); +``` + +- A: `🤠` +- B: `🥰` +- C: `SyntaxError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me operandin `+=`, ne po rrisim vlerën e `sum` për `1`. `num` kishte vlerën iniciale `1`, kështu `1 + 1` është `2`. Elementi në indeksin e dytë në `list` është 🥰, `console.log(list[2])` printon 🥰. + +

+
+ +--- + +###### 119. Cila është vlera e saj? + +```javascript +const person = { + firstName: 'Lydia', + lastName: 'Hallie', + pet: { + name: 'Mara', + breed: 'Dutch Tulip Hound', + }, + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, +}; + +console.log(person.pet?.name); +console.log(person.pet?.family?.name); +console.log(person.getFullName?.()); +console.log(member.getLastName?.()); +``` + +- A: `undefined` `undefined` `undefined` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` +- C: `Mara` `null` `Lydia Hallie` `null` +- D: `null` `ReferenceError` `null` `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Me operatorin opsional të zinxhirit `?.`, nuk duhet të kontrollojmë më në mënyrë eksplicite nëse vlerat më të thella të ndërthurura janë të vlefshme apo jo. Nëse po provojmë ti qasemi një vetie me një vlerë `undefined` ose `null` (_nullish_), shprehja lidhet me qark të shkurtër dhe kthen `undefined`. + +`person.pet?.name`: `person` ka një veti të quajtur `pet`: `person.pet` nuk është vlerë null. Ka një veti të quajtur `name`, dhe kthen `Mara`. +`person.pet?.family?.name`: `person` ka një veti të quajtur `pet`: `person.pet` nuk është vlerë null. `pet` nuk ka një veti të quajtur `family`, `person.pet.family` është vlerë null. Shprehja kthen `undefined`. +`person.getFullName?.()`: `person` ka një veti të quajtur `getFullName`: `person.getFullName()` nuk është vlerë null dhe mund të thirret, dhe do të kthejë `Lydia Hallie`. +`member.getLastName?.()`: variabla `member` nuk ekziston prandaj `ReferenceError` do të hedhet! + +

+
+ +--- + +###### 120. Cila është vlera e saj? + +```javascript +const groceries = ['banana', 'apple', 'peanuts']; + +if (groceries.indexOf('banana')) { + console.log('We have to buy bananas!'); +} else { + console.log(`We don't have to buy bananas!`); +} +``` + +- A: We have to buy bananas! +- B: We don't have to buy bananas +- C: `undefined` +- D: `1` + +
Përgjigja +

+ +#### Përgjigja: B + +Ne e kaluam kushtëzimin `groceries.indexOf("banana")` tek deklarimi if. `groceries.indexOf("banana")` kthen `0`, e cila është vlerë false. Përderisa deklarimi i kushtëzimit if është falsy, kodi në bllokun `else` ekzekutohet, dhe `We don't have to buy bananas!` do të printohet. + +

+
+ +--- + +###### 121. Cila është vlera e saj? + +```javascript +const config = { + languages: [], + set language(lang) { + return this.languages.push(lang); + }, +}; + +console.log(config.language); +``` + +- A: `function language(lang) { this.languages.push(lang }` +- B: `0` +- C: `[]` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `language` është metodë `setter` (vendosëse). Vendosësit nuk mbajë një vlerë aktuale, qêllimi i tyre është të _modifikojnë_ vetitë. Kur e thirrim metodën `setter`, do të kthehet `undefined`. + +

+
+ +--- + +###### 122. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; + +console.log(!typeof name === 'object'); +console.log(!typeof name === 'string'); +``` + +- A: `false` `true` +- B: `true` `false` +- C: `false` `false` +- D: `true` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +`typeof name` kthen `"string"`. Stringu `"string"` është vlerë truthy, kështu që `!typeof name` kthen vlerën booleane `false`. `false === "object"` dhe `false === "string"` të dy kthejnë `false`. + +(Nëse do të dëshironim të shikojmë në qoftëse tipi ishtë (jo) i barabartë në një tip të caktuar, do të kishim shkruar `!==` në vend të `!typeof`) + +

+
+ +--- + +###### 123. Cila është vlera e saj? + +```javascript +const add = x => y => z => { + console.log(x, y, z); + return x + y + z; +}; + +add(4)(5)(6); +``` + +- A: `4` `5` `6` +- B: `6` `5` `4` +- C: `4` `function` `function` +- D: `undefined` `undefined` `6` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `add` kthen një funksion shigjete, i cili kthen një funksion shigjete, i cili kthen një funksion shigjete. Funksioni i parë merr një argument `x` me vlerën `4`. Ne e thërrasim funksionin e dytë, i cili merr një argument `y` me vlerën `5`. Pastaj thërrasim funksionin e tretë, i cili merr një argument `z` me vlerën `6`. Kur po provojmë të qasemi në vlerën `x`, `y` dhe `z` brenda funksionit të fundit të shigjetës, makina JS shkon lart në zinxhirin e shtrirjes për të gjetur vlerat për `x` dhe `y` përkatësisht. Kjo kthen `4` `5` `6`. + +

+
+ +--- + +###### 124. Cila është vlera e saj? + +```javascript +async function* range(start, end) { + for (let i = start; i <= end; i++) { + yield Promise.resolve(i); + } +} + +(async () => { + const gen = range(1, 3); + for await (const item of gen) { + console.log(item); + } +})(); +``` + +- A: `Promise {1}` `Promise {2}` `Promise {3}` +- B: `Promise {}` `Promise {}` `Promise {}` +- C: `1` `2` `3` +- D: `undefined` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni gjenerator `range` kthen një objekt asinkron me premtimet për çdo elemnt në rangun që ne japim: `Promise{1}`, `Promise{2}`, `Promise{3}`. Ne vendosim variablën `gen` të jetë e barabartë me objektin asinkron, pas të cilit ne e iterojmë mbi të nëpërmjet unazës `for await ... of`. Ne vendosim variablën `item` të jetë e barabartë me vlerat e kthyera të Promise: së pari `Promise{1}`, pastaj `Promise{2}`, pastaj `Promise{3}`. Pasi që po _presim_ vlerën e `item`, premtimet e zgjidhura, vlerat e zgjidhura të premtimit kthehen: `1`, `2`, pastaj `3`. + +

+
+ +--- + +###### 125. Cila është vlera e saj? + +```javascript +const myFunc = ({ x, y, z }) => { + console.log(x, y, z); +}; + +myFunc(1, 2, 3); +``` + +- A: `1` `2` `3` +- B: `{1: 1}` `{2: 2}` `{3: 3}` +- C: `{ 1: undefined }` `undefined` `undefined` +- D: `undefined` `undefined` `undefined` + +
Përgjigja +

+ +#### Përgjigja: D + +`myFunc` pret një objekt me vetitë `x`, `y` dhe `z` si argumente të tij. Pasi që po japim vetëm tre vlera numerike të ndara (1, 2, 3) në vend të një objekti me vetitë `x`, `y` dhe `z` ({x: 1, y: 2, z: 3}), `x`, `y` dhe `z` kanë vlerën e tyre të parazgjedhur si `undefined`. + +

+
+ +--- + +###### 126. Cila është vlera e saj? + +```javascript +function getFine(speed, amount) { + const formattedSpeed = new Intl.NumberFormat('en-US', { + style: 'unit', + unit: 'mile-per-hour' + }).format(speed); + + const formattedAmount = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount); + + return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`; +} + +console.log(getFine(130, 300)) +``` + +- A: The driver drove 130 and has to pay 300 +- B: The driver drove 130 mph and has to pay \$300.00 +- C: The driver drove undefined and has to pay undefined +- D: The driver drove 130.00 and has to pay 300.00 + +
Përgjigja +

+ +#### Përgjigja: B + +Me metoden `Intl.NumberFormat`, ne mund të formatojmë vlerat numerike në çdo vend. Ne formatojmë vlerën numerike `130` në vendin `en-US` si një `unit` në `mile-per-hour`, që rezulton në `130 mph`. Vlera numerike `300` në vendin `en-US` si një `currency` në `USD` rezulton në `$300.00`. + +

+
+ +--- + +###### 127. Cila është vlera e saj? + +```javascript +const spookyItems = ['👻', '🎃', '🕸']; +({ item: spookyItems[3] } = { item: '💀' }); + +console.log(spookyItems); +``` + +- A: `["👻", "🎃", "🕸"]` +- B: `["👻", "🎃", "🕸", "💀"]` +- C: `["👻", "🎃", "🕸", { item: "💀" }]` +- D: `["👻", "🎃", "🕸", "[object Object]"]` + +
Përgjigja +

+ +#### Përgjigja: B + +Duke destrukturuar objektet, ne mund të targetojmë vlerat nga objekti i djathtë, dhe të caktojmë vlerën e targetuar në vlerën e emrit të njëjtë të vetisë në objektin në anën e majtë. Në këtë rast, ne po caktojmë vlerën "💀" në `spookyItems[3]`. Kjo do të thotë se ne po ndryshojmë vargun `spookyItems`, po i shtojmë "💀". Kur printojmë `spookyItems`, `["👻", "🎃", "🕸", "💀"]` printohet. + +

+
+ +--- + +###### 128. Cila është vlera e saj? + +```javascript +const name = 'Lydia Hallie'; +const age = 21; + +console.log(Number.isNaN(name)); +console.log(Number.isNaN(age)); + +console.log(isNaN(name)); +console.log(isNaN(age)); +``` + +- A: `true` `false` `true` `false` +- B: `true` `false` `false` `false` +- C: `false` `false` `true` `false` +- D: `false` `true` `false` `true` + +
Përgjigja +

+ +#### Përgjigja: C + +Me metoden `Number.isNaN`, ju mund të kontrolloni nëse vlera që ju jepni është një _vlerë numerike_ dhe e barabartë me `NaN`. `name` nuk është një vlerë numerike, kështu që `Number.isNaN(name)` kthen `false`. `age` është një vlerë numerike, por nuk është e barabartë me `NaN`, kështu që `Number.isNaN(age)` kthen `false`. + +Me metoden `isNaN`, ju mund të kontrolloni nëse vlera që ju jepni nuk është numër. `name` nuk është numër, kështu që `isNaN(name)` kthen true. `age` është numër, kështu që `isNaN(age)` kthen `false`. + +

+
+ +--- + +###### 129. Cila është vlera e saj? + +```javascript +const randomValue = 21; + +function getInfo() { + console.log(typeof randomValue); + const randomValue = 'Lydia Hallie'; +} + +getInfo(); +``` + +- A: `"number"` +- B: `"string"` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: D + +Variablat e deklaruara me fjalën kyçe `const` nuk janë të referueshme para inicializimit të tyre: kjo quhet _zona e vdekjes së përkohshme_. Në funksionin `getInfo`, variabla `randomValue` është me shtrirje në fushën e funksionit `getInfo`. Në rreshtin ku ne duam të printojmë vlerën e `typeof randomValue`, variabla `randomValue` nuk është inicializuar ende: një `ReferenceError` hidhet! Makina e JS nuk shkoi poshtë në zinxhirin e fushës pasi ne deklaruam variablën `randomValue` në funksionin `getInfo`. + +

+
+ +--- + +###### 130. Cila është vlera e saj? + +```javascript +const myPromise = Promise.resolve('Woah some cool data'); + +(async () => { + try { + console.log(await myPromise); + } catch { + throw new Error(`Oops didn't work`); + } finally { + console.log('Oh finally!'); + } +})(); +``` + +- A: `Woah some cool data` +- B: `Oh finally!` +- C: `Woah some cool data` `Oh finally!` +- D: `Oops didn't work` `Oh finally!` + +
Përgjigja +

+ +#### Përgjigja: C + +Në bllokun `try`, ne jemi duke printuar vlerën e pritur të variablës `myPromise`: `"Woah some cool data"`. Pasi që nuk u hodhën gabime në bllokun `try`, kodi në bllokun `catch` nuk ekzekutohet. Kodi në bllokun `finally` _gjithmonë_ ekzekutohet, `"Oh finally!"` printohet. + +

+
+ +--- + +###### 131. Cila është vlera e saj? + +```javascript +const emojis = ['🥑', ['✨', '✨', ['🍕', '🍕']]]; + +console.log(emojis.flat(1)); +``` + +- A: `['🥑', ['✨', '✨', ['🍕', '🍕']]]` +- B: `['🥑', '✨', '✨', ['🍕', '🍕']]` +- C: `['🥑', ['✨', '✨', '🍕', '🍕']]` +- D: `['🥑', '✨', '✨', '🍕', '🍕']` + +
Përgjigja +

+ +#### Përgjigja: B + +Me metodën flat, ne mund të krijojmë një varg të ri, të rrafshët. Thellësia e vargut të rrafshët varet nga vlera që ne japim. Në këtë rast, ne dhamë vlerën 1 (e cila nuk ishte e nevojshme, ajo është vlera e paracaktuar), që do të thotë se vetëm vargjet në thellësinë e parë do të bashkohen. ['🥑'] dhe ['✨', '✨', ['🍕', '🍕']] në këtë rast. Bashkimi i këtyre dy vargjeve rezulton në ['🥑', '✨', '✨', ['🍕', '🍕']]. + +

+
+ +--- + +###### 132. Cila është vlera e saj? + +```javascript +class Counter { + constructor() { + this.count = 0; + } + + increment() { + this.count++; + } +} + +const counterOne = new Counter(); +counterOne.increment(); +counterOne.increment(); + +const counterTwo = counterOne; +counterTwo.increment(); + +console.log(counterOne.count); +``` + +- A: `0` +- B: `1` +- C: `2` +- D: `3` + +
Përgjigja +

+ +#### Përgjigja: D + +`counterOne` është një instancë e klasës `Counter`. Klasa Counter përmban një veti `count` në konstruktorin e saj, dhe një metodë `increment`. Së pari, ne thirrëm metodën `increment` dy herë duke thirrur `counterOne.increment()`. Aktualisht, `counterOne.count` është `2`. + + + +Më pas, ne krijojmë një variabël të re `counterTwo`, dhe e vendosim të barabartë me `counterOne`. Pasi objektet ndërveprojnë me referencë, ne thjesht po krijojmë një referencë të re për të njëjtin vend në memorie ku `counterOne` tregon. Meqenëse po tregon në të njëjtin vend në memorie, çdo ndryshim i bërë në objektin që `counterTwo` ka një referencë, gjithashtu vlen edhe për `counterOne`. Aktualisht, `counterTwo.count` është `2`. + +Ne thërrasim `counterTwo.increment()`, i cili vendos `count` në `3`. Pastaj, printojmë numëruesin `counterOne`, i cili printon `3`. + + + +

+
+ +--- + +###### 133. Cila është vlera e saj? + +```javascript +const myPromise = Promise.resolve(Promise.resolve('Promise')); + +function funcOne() { + setTimeout(() => console.log('Timeout 1!'), 0); + myPromise.then(res => res).then(res => console.log(`${res} 1!`)); + console.log('Last line 1!'); +} + +async function funcTwo() { + const res = await myPromise; + console.log(`${res} 2!`) + setTimeout(() => console.log('Timeout 2!'), 0); + console.log('Last line 2!'); +} + +funcOne(); +funcTwo(); +``` + +- A: `Promise 1! Last line 1! Promise 2! Last line 2! Timeout 1! Timeout 2!` +- B: `Last line 1! Timeout 1! Promise 1! Last line 2! Promise2! Timeout 2! ` +- C: `Last line 1! Promise 2! Last line 2! Promise 1! Timeout 1! Timeout 2!` +- D: `Timeout 1! Promise 1! Last line 1! Promise 2! Timeout 2! Last line 2!` + +
Përgjigja +

+ +#### Përgjigja: C + +Së pari, ne thirrim `funcOne`. Në rreshtin e parë të `funcOne`, ne thirrim funksionin _asinkron_ `setTimeout`, nga i cili callback është dërguar tek API-ja e Web-it. (shih artikullin tim mbi ciklin e ngjarjeve këtu.) + +Pastaj e thirrim premtimin `myPromise`, e cila është një operacion _asinkron_. + +Edhe premtimi dhe koha e pritjes janë operacione asinkrone, funksioni vazhdon të ekzekutohet ndërsa është i zënë në plotësimin e premtimeve dhe trajtimin e callback-ut `setTimeout`. Kjo do të thotë se `Last line 1!` printohet së pari, pasi kjo nuk është një operacion asinkron. + +Meqenëse callstack nuk është bosh ende, funksioni `setTimeout` dhe premtimi në `funcOne` nuk mund të shtohen ende në callstack. + +Në `funcTwo`, variabla `res` merr `Promise` sepse `Promise.resolve(Promise.resolve('Promise'))` është ekuivalente me `Promise.resolve('Promise')` pasi plotësimi i një premtimi thjesht i plotëson vlerat e tij. `await` në këtë rresht ndalon ekzekutimin e funksionit derisa të marrë zgjidhjen e premtimit dhe pastaj vazhdon të ekzekutohet sinkronisht deri në përfundim, kështu që `Promise 2!` dhe pastaj `Last line 2!` janë regjistruar dhe `setTimeout` është dërguar tek API-ja e Web-it. + +Pastaj call stack është bosh. Premtimet janë _mikrodetyra_ (microtasks) prandaj ato zgjidhen së pari kur call stack është bosh, kështu që `Promise 1!` printohet. + +Tani, pasi që `funcTwo` është larguar nga call stack, call stack është bosh. Callback-et që po presin në radhë (`() => console.log("Timeout 1!")` nga `funcOne`, dhe `() => console.log("Timeout 2!")` nga `funcTwo`) shtohen në call stack një nga një. Callback-i i parë printon `Timeout 1!`, dhe largohet nga stack. Më pas, callback-i i dytë printon `Timeout 2!`, dhe largohet nga stack. + +

+
+ +--- + +###### 134. Si mund të thërrasim funksionin `sum` nga `sum.js` në `index.js`? + +```javascript +// sum.js +export default function sum(x) { + return x + x; +} + +// index.js +import * as sum from './sum'; +``` + +- A: `sum(4)` +- B: `sum.sum(4)` +- C: `sum.default(4)` +- D: Eksportimet e paracaktuar nuk importohen me `*`, vetëm eksportimet e emëruara. + +
Përgjigja +

+ +#### Përgjigja: C + +Me yllin `*`, ne importojmë të gjitha vlerat e eksportuara nga ai fajll, si ato të paracaktuara dhe ato të emëruara. Nëse kemi fajllin e mëposhtëm: + +```javascript +// info.js +export const name = 'Lydia'; +export const age = 21; +export default 'I love JavaScript'; + +// index.js +import * as info from './info'; +console.log(info); +``` + +The following would get logged: + +```javascript +{ + default: "I love JavaScript", + name: "Lydia", + age: 21 +} +``` + +Për shembullin `sum`, do të thotë se vlera e importuar e `sum` do të dukej kështu: + +```javascript +{ default: function sum(x) { return x + x } } +``` + +Mund të e thërrasim këtë funksion, duke thirrur `sum.default` + +

+
+ +--- + +###### 135. Cila është vlera e saj? + +```javascript +const handler = { + set: () => console.log('Added a new property!'), + get: () => console.log('Accessed a property!'), +}; + +const person = new Proxy({}, handler); + +person.name = 'Lydia'; +person.name; +``` + +- A: `Added a new property!` +- B: `Accessed a property!` +- C: `Added a new property!` `Accessed a property!` +- D: Asgjë nuk printohet + +
Përgjigja +

+ +#### Përgjigja: C + +Me një objekt Proxy, ne mund të shtojmë sjellje të personalizuara për një objekt të cilit i kalohet si argumenti i dytë. Në këtë rast, ne i kalojmë objektin `handler` i cili përmban dy veti: `set` dhe `get`. `set` thirret çdo herë kur ne _caktojmë_ vlerat e vetisë, `get` thirret çdo herë kur ne _marrim_ (i qasemi) vlerave të vetisë. + +Argumenti i parë është një objekt i zbrazët `{}`, i cili është vlera e `person`. Tek ky objekt, shtohet sjellja e personalizuar e specifikuar në objektin `handler`. Nëse shtojmë një veti tek objekti `person`, `set` do të thirret. Nëse i qasemi një vetie në objektin `person`, `get` do të thirret. + +Së pari, ne shtuam një veti të re `name` tek objekti proxy (`person.name = "Lydia"`). `set` thirret, dhe printon `"Added a new property!"`. + +Pastaj, ne i qasemi një vlerë të vetisë në objektin proxy, vetia `get` në objektin handler thirret. `"Accessed a property!"` printohet. + +

+
+ +--- + +###### 136. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? + +```javascript +const person = { name: 'Lydia Hallie' }; + +Object.seal(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `person.age = 21` +- C: `delete person.name` +- D: `Object.assign(person, { age: 21 })` + +
Përgjigja +

+ +#### Përgjigja: A + +Me `Object.seal` ne mund të parandalojmë shtimin e vetive të reja, ose fshirjen e vetive ekzistuese. + +Megjithatë, ju ende mund të modifikoni vlerën e vetive ekzistuese. + +

+
+ +--- + +###### 137. Cili nga opsionet e mëposhtme do të modifikojë objektin `person`? + +```javascript +const person = { + name: 'Lydia Hallie', + address: { + street: '100 Main St', + }, +}; + +Object.freeze(person); +``` + +- A: `person.name = "Evan Bacon"` +- B: `delete person.address` +- C: `person.address.street = "101 Main St"` +- D: `person.pet = { name: "Mara" }` + +
Përgjigja +

+ +#### Përgjigja: C + +Metoda `Object.freeze` _ngrin_ një objekt. Asnjë veti nuk mund të shtohet, të modifikohet, ose të hiqet. + +Megjithatë, ajo vetëm _ngrin sipërfaqësisht_ objektin, që do të thotë se vetëm vetitë _e drejtpërdrejta_ në objekt janë të ngrira. Nëse vetia është një tjetër objekt, si `address` në këtë rast, vetitë në atë objekt nuk janë të ngrira, dhe mund të modifikohen. + +

+
+ +--- + +###### 138. Cila është vlera e saj? + +```javascript +const add = x => x + x; + +function myFunc(num = 2, value = add(num)) { + console.log(num, value); +} + +myFunc(); +myFunc(3); +``` + +- A: `2` `4` and `3` `6` +- B: `2` `NaN` and `3` `NaN` +- C: `2` `Error` and `3` `6` +- D: `2` `4` and `3` `Error` + +
Përgjigja +

+ +#### Përgjigja: A + +Së pari, ne thirrëm `myFunc()` pa kaluar asnjë argument. Pasi që nuk kaluam argumente, `num` dhe `value` morën vlerat e tyre të paracaktuara: num është `2`, dhe `value` është vlera e kthyer nga funksioni `add`. Tek funksioni `add`, ne i japim si argument `num`, i cili ka vlerën `2`. `Add` kthen `4`, e cila është vlera e `value`. + +Më pas, ne thirrëm `myFunc(3)` dhe kaluam vlerën `3` si vlerë për argumentin `num`. Nuk kaluam një argument për `value`. Pasi nuk kaluam një vlerë për argumentin `value`, ai mori vlerën e paracaktuar: vlerën e kthyer nga funksioni `add`. Tek `add`, ne i japim si argument `num`, i cili ka vlerën `3`. `Add` kthen `6`, e cila është vlera e `value`. + +

+
+ +--- + +###### 139. Cila është vlera e saj? + +```javascript +class Counter { + #number = 10 + + increment() { + this.#number++ + } + + getNum() { + return this.#number + } +} + +const counter = new Counter() +counter.increment() + +console.log(counter.#number) +``` + +- A: `10` +- B: `11` +- C: `undefined` +- D: `SyntaxError` + +
Përgjigja +

+ +#### Përgjigja: D + +Në ES2020, mund të shtojmë variabla private në klasa duke përdorur `#`. Nuk mund t'i qasemi këtyre variablave jashtë klasës. Kur provojmë të printojmë `counter.#number`, hidhet një SyntaxError: nuk mund t'i qaseni jashtë klasës `Counter`! + +

+
+ +--- + +###### 140. Çfarë po mungon? + +```javascript +const teams = [ + { name: 'Team 1', members: ['Paul', 'Lisa'] }, + { name: 'Team 2', members: ['Laura', 'Tim'] }, +]; + +function* getMembers(members) { + for (let i = 0; i < members.length; i++) { + yield members[i]; + } +} + +function* getTeams(teams) { + for (let i = 0; i < teams.length; i++) { + // ✨ SOMETHING IS MISSING HERE ✨ + } +} + +const obj = getTeams(teams); +obj.next(); // { value: "Paul", done: false } +obj.next(); // { value: "Lisa", done: false } +``` + +- A: `yield getMembers(teams[i].members)` +- B: `yield* getMembers(teams[i].members)` +- C: `return getMembers(teams[i].members)` +- D: `return yield getMembers(teams[i].members)` + +
Përgjigja +

+ +#### Përgjigja: B + +Për të iteruar mbi `members` në çdo element në array `teams`, duhet të kaloni `teams[i].members` në funksionin gjenerator `getMembers`. Funksioni gjenerator kthen një objekt gjenerator. Për të iteruar mbi çdo element në këtë objekt gjenerator, duhet të përdorim `yield*`. + +Nëse do të shkruanim `yield`, `return yield`, ose `return`, gjithë funksioni gjenerator do të kthehej herën e parë që do e thirrim metodën `next`. + +

+
+ +--- + +###### 141. Cila është vlera e saj? + +```javascript +const person = { + name: 'Lydia Hallie', + hobbies: ['coding'], +}; + +function addHobby(hobby, hobbies = person.hobbies) { + hobbies.push(hobby); + return hobbies; +} + +addHobby('running', []); +addHobby('dancing'); +addHobby('baking', person.hobbies); + +console.log(person.hobbies); +``` + +- A: `["coding"]` +- B: `["coding", "dancing"]` +- C: `["coding", "dancing", "baking"]` +- D: `["coding", "running", "dancing", "baking"]` + +
Përgjigja +

+ +#### Përgjigja: C + +Funksioni `addHobby` merr dy argumente, `hobby` dhe `hobbies` me vlerën e paracaktuar të array `hobbies` në objektin `person`. + +Së pari, ne thirrim funksionin `addHobby`, dhe japim `"running"` si vlerë për `hobby` dhe një array bosh si vlerë për `hobbies`. Pasi japim një varg bosh si vlerë për `hobbies`, `"running"` shtohet në këtë varg bosh. + +Pastaj, ne thirrim funksionin `addHobby`, dhe japim `"dancing"` si vlerë për `hobby`. Nuk kemi dhënë vlerë për `hobbies`, kështu që ajo merr vlerën e paracaktuar, vetinë `hobbies` në objektin `person`. Ne shtojmë hobi `dancing` në array `person.hobbies`. + +Në fund, ne thirrim funksionin `addHobby`, dhe japim `"baking"` si vlerë për `hobby`, dhe array `person.hobbies` si vlerë për `hobbies`. Ne shtojmë hobi `baking` në array `person.hobbies`. + +Pas shtimit të `dancing` dhe `baking`, vlera e `person.hobbies` është `["coding", "dancing", "baking"]` + +

+
+ +--- + +###### 142. Cila është vlera e saj? + +```javascript +class Bird { + constructor() { + console.log("I'm a bird. 🦢"); + } +} + +class Flamingo extends Bird { + constructor() { + console.log("I'm pink. 🌸"); + super(); + } +} + +const pet = new Flamingo(); +``` + +- A: `I'm pink. 🌸` +- B: `I'm pink. 🌸` `I'm a bird. 🦢` +- C: `I'm a bird. 🦢` `I'm pink. 🌸` +- D: Asgjë, ne nuk kemi thirrur ndonjë metodë. + +
Përgjigja +

+ +#### Përgjigja: B + +Krijojmë variablën `pet` që është një instancë e klasës `Flamingo`. Kur ne e instantojmë këtë instancë, thirret `constructor` në `Flamingo`. Së pari, `"I'm pink. 🌸"` printohet, pas të cilit thirrim `super()`. `super()` thirr constructorin e klasës prind, `Bird`. Thirret constructori në `Bird`, dhe printon `"I'm a bird. 🦢"`. + +

+
+ +--- + +###### 143. Cila nga opsionet rezulton me gabim? + +```javascript +const emojis = ['🎄', '🎅🏼', '🎁', '⭐']; + +/* 1 */ emojis.push('🦌'); +/* 2 */ emojis.splice(0, 2); +/* 3 */ emojis = [...emojis, '🥂']; +/* 4 */ emojis.length = 0; +``` + +- A: 1 +- B: 1 and 2 +- C: 3 and 4 +- D: 3 + +
Përgjigja +

+ +#### Përgjigja: D + +Fjala kyçe `const` thjesht do të thotë se nuk mund të _ri-deklarojmë_ vlerën e asaj ndryshore, është _vetëm për lexim_. Megjithatë, vlera e elementeve të array nuk është e pandryshueshme. Vetitë në vargun `emojis` mund të modifikohen, për shembull duke shtuar vlera të reja, duke i shpërndarë ato, ose duke caktuar gjatësinë e vargut në 0. + +

+
+ +--- + +###### 144. Çfarë duhet të shtojmë në objektin `person` për të marrë `["Lydia Hallie", 21]` si rezultat të `[...person]`? + +```javascript +const person = { + name: "Lydia Hallie", + age: 21 +} + +[...person] // ["Lydia Hallie", 21] +``` + +- A: Asgjë, objektet janë të iterueshme paraprakisht. +- B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` +- D: `*[Symbol.iterator]() { for (let x in this) yield this }` + +
Përgjigja +

+ +#### Përgjigja: C + +Objektet nuk janë të paraprakisht të iterueshme. Një objekt është i iterueshëm nëse protokolli i iteratorëve është prezent. Ne mund ta shtojmë këtë manualisht duke shtuar simbolin e iteratorit `[Symbol.iterator]`, i cili duhet të kthejë një objekt gjenerator, për shembull duke e bërë atë një funksion gjenerator `*[Symbol.iterator]() {}`. Ky funksion gjenerator duhet të prodhojë `Object.values` e objektit `person` nëse dëshirojmë që të kthejë array `["Lydia Hallie", 21]`: `yield* Object.values(this)`. + +

+
+ +--- + +###### 145. Cila është vlera e saj? + +```javascript +let count = 0; +const nums = [0, 1, 2, 3]; + +nums.forEach(num => { + if (num) count += 1 +}) + +console.log(count) +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
Përgjigja +

+ +#### Përgjigja: C + +Kushti `if` brenda ciklit `forEach` kontrollon nëse vlera e `num` është e vërtetë apo false. Meqenëse numri i parë në array `nums` është `0`, një vlerë false, blloku i kodit të deklaratës `if` nuk do të ekzekutohet. `count` rritet vetëm për 3 numrat e tjerë në array `nums`, `1`, `2` dhe `3`. Meqenëse `count` rritet për `1` 3 herë, vlera e `count` është `3`. + +

+
+ +--- + +###### 146. Cila është vlera e saj? + +```javascript +function getFruit(fruits) { + console.log(fruits?.[1]?.[1]) +} + +getFruit([['🍊', '🍌'], ['🍍']]) +getFruit() +getFruit([['🍍'], ['🍊', '🍌']]) +``` + +- A: `null`, `undefined`, 🍌 +- B: `[]`, `null`, 🍌 +- C: `[]`, `[]`, 🍌 +- D: `undefined`, `undefined`, 🍌 + +
Përgjigja +

+ +#### Përgjigja: D + +Simboli ? na lejon të i qasemi opsionalisht vetive më të thella brenda objekteve. Ne po provojmë të shfaqim elementin në indeksin 1 brenda në nën-array që është në indeksin 1 të array fruits. Nëse nën-array në indeksin 1 në array fruits nuk ekziston, thjesht do të kthejë undefined. Nëse nën-array në indeksin 1 në vargun fruits ekziston, por ky nën-array nuk ka një artikull në indeksin e tij 1, gjithashtu do të kthejë undefined. + +Së pari, ne po përpiqemi të printojmë artikullin e dytë në nën-array `['🍍']` të `[['🍊', '🍌'], ['🍍']]`. Ky nën-array përmban vetëm një element, që do të thotë se nuk ka element në indeksin `1`, dhe kthen `undefined`. + +Më pas, ne po thërrasim funksionin `getFruits` pa kaluar një vlerë si argument, që do të thotë se `fruits` ka vlerë `undefined` të paracaktuar. Pasi që po lidhim në mënyrë kushtëzuese elementin në indeksin `1` të `fruits`, kthen `undefined` pasi ky element në indeksin `1` nuk ekziston. + +Së fundmi, po përpiqemi të shfaqim artikullin e dytë në nën-array `['🍊', '🍌']` të `['🍍'], ['🍊', '🍌']`. Elementi në indeksin `1` brenda këtij nën-array është `🍌` që printohet. + +

+
+ +--- + +###### 147. Cila është vlera e saj? + +```javascript +class Calc { + constructor() { + this.count = 0 + } + + increase() { + this.count++ + } +} + +const calc = new Calc() +new Calc().increase() + +console.log(calc.count) +``` + +- A: `0` +- B: `1` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Ne i caktojmë variablës `calc` të jetë e barabartë me një instancë të re të klasës `Calc`. Më pas, ne krijojmë një instancë të re të `Calc`, dhe thërrasim metodën `increase` në këtë instancë. Pasi që vetia 'count' është brenda konstruktorit të klasës `Calc`, vetia 'calc' nuk është e përbashkët në prototipin e `Calc`. Kjo do të thotë se vlera 'calc' nuk është përditësuar për instancën që tregon calc, numërimi është ende `0`. + +

+
+ +--- + +###### 148. Cila është vlera e saj? + +```javascript +const user = { + email: "e@mail.com", + password: "12345" +} + +const updateUser = ({ email, password }) => { + if (email) { + Object.assign(user, { email }) + } + + if (password) { + user.password = password + } + + return user +} + +const updatedUser = updateUser({ email: "new@email.com" }) + +console.log(updatedUser === user) +``` + +- A: `false` +- B: `true` +- C: `TypeError` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Funksioni `updateUser` përditëson vlerat e vetive `email` dhe `password` në user, nëse vlerat e tyre i janë kaluar funksionit, pas së cilës funksioni kthen objektin `user`. Vlera e kthyer e funksionit `updateUser` është objekti `user`, që do të thotë se vlera e updatedUser është një referencë për të njëjtin objekt `user` që tregon `user`. `updatedUser === user` është e barabartë me `true`. + +

+
+ +--- + +###### 149. Cila është vlera e saj? + +```javascript +const fruit = ['🍌', '🍊', '🍎'] + +fruit.slice(0, 1) +fruit.splice(0, 1) +fruit.unshift('🍇') + +console.log(fruit) +``` + +- A: `['🍌', '🍊', '🍎']` +- B: `['🍊', '🍎']` +- C: `['🍇', '🍊', '🍎']` +- D: `['🍇', '🍌', '🍊', '🍎']` + +
Përgjigja +

+ +#### Përgjigja: C + +Së pari, ne thirrim metodën `slice` në array e frutave. Metoda slice nuk modifikon array origjinal, por kthen vlerën që e ka 'prerë (slice)' nga array: emoji e bananes. +Më pas, ne thirrim metodën `splice` në array e frutave. Metoda splice modifikon array origjinal, që do të thotë se array i frutave tani përbëhet nga `['🍊', '🍎']`. +Në fund, ne thirrim metodën `unshift` në array e frutave, e cila modifikon array origjinal duke shtuar vlerën e dhënë, në këtë rast ‘🍇’, si elementin e parë në varg. Array i frutave tani përbëhet nga `['🍇', '🍊', '🍎']`. + +

+
+ +--- + +###### 150. Cila është vlera e saj? + +```javascript +const animals = {}; +let dog = { emoji: '🐶' } +let cat = { emoji: '🐈' } + +animals[dog] = { ...dog, name: "Mara" } +animals[cat] = { ...cat, name: "Sara" } + +console.log(animals[dog]) +``` + +- A: `{ emoji: "🐶", name: "Mara" }` +- B: `{ emoji: "🐈", name: "Sara" }` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: B + +Çelësat e objektit konvertohen në stringje. + +Pasi që vlera e `dog` është një objekt, `animals[dog]` në fakt do të thotë që ne po krijojmë një veti të re të quajtur `"object Object"` të barabartë me objektin e ri. Tani `animals["object Object"]` është i barabartë me `{ emoji: "🐶", name: "Mara"}`. + +`cat` është gjithashtu një objekt, që do të thotë që `animals[cat]` në fakt do të thotë se ne po mbishkruajmë vlerën e `animals["object Object"]` me vetitë e reja të macës. + +Duke printuar `animals[dog]`, ose në fakt `animals["object Object"]` pasi që konvertimi i objektit `dog` në string rezulton në `"object Object"`, kthen `{ emoji: "🐈", name: "Sara" }`. + +

+
+ +--- + +###### 151. Cila është vlera e saj? + +```javascript +const user = { + email: "my@email.com", + updateEmail: email => { + this.email = email + } +} + +user.updateEmail("new@email.com") +console.log(user.email) +``` + +- A: `my@email.com` +- B: `new@email.com` +- C: `undefined` +- D: `ReferenceError` + +
Përgjigja +

+ +#### Përgjigja: A + +Funksioni `updateEmail` është një funksion shigjetë dhe nuk është i lidhur me objektin `user`. Kjo do të thotë se fjalë kyçe `this` nuk i referohet objektit `user`, por i referohet shtrirjes globale në këtë rast. Vlera e `email` brenda objektit `user` nuk përditësohet. Kur printohet vlera e `user.email`, kthehet vlera origjinale e `my@email.com`. + +

+
+ +--- + +###### 152. Cila është vlera e saj? + +```javascript +const promise1 = Promise.resolve('First') +const promise2 = Promise.resolve('Second') +const promise3 = Promise.reject('Third') +const promise4 = Promise.resolve('Fourth') + +const runPromises = async () => { + const res1 = await Promise.all([promise1, promise2]) + const res2 = await Promise.all([promise3, promise4]) + return [res1, res2] +} + +runPromises() + .then(res => console.log(res)) + .catch(err => console.log(err)) +``` + +- A: `[['First', 'Second'], ['Fourth']]` +- B: `[['First', 'Second'], ['Third', 'Fourth']]` +- C: `[['First', 'Second']]` +- D: `'Third'` + +
Përgjigja +

+ +#### Përgjigja: D + +Metoda `Promise.all` ekzekuton premtimet e dhëna si argumente paralelisht. Nëse një premtim dështon, metoda 'Promise.all' _refuzon_ me vlerën e premtimit të refuzuar. Në këtë rast, `promise3` u refuzua me vlerën `"Third"`. Ne po kapim vlerën e refuzuar në metodën `catch` në thirrjen `runPromises` për të kapur çdo gabim brenda funksionit `runPromises`. Vetëm `"Third"` printohet, pasi `promise3` u refuzua me këtë vlerë. + +

+
+ +--- + +###### 153. Cila duhet të jetë vlera e `method` për të printuar `{ name: "Lydia", age: 22 }`? + +```javascript +const keys = ["name", "age"] +const values = ["Lydia", 22] + +const method = /* ?? */ +Object[method](keys.map((_, i) => { + return [keys[i], values[i]] +})) // { name: "Lydia", age: 22 } +``` + +- A: `entries` +- B: `values` +- C: `fromEntries` +- D: `forEach` + +
Përgjigja +

+ +#### Përgjigja: C + +Metoda `fromEntries` transformon një array 2d në një objekt. Elementi i parë në çdo nën-array do të jetë çelësi, dhe elementi i dytë në çdo nën-array do të jetë vlera. Në këtë rast, ne jemi duke mapuar mbi array `keys`, i cili kthen një array ku elementi i parë është elementi në array të çelësave në indeksin aktual, dhe elementi i dytë është elementi i vlerave të array në indeksin aktual. + +Kjo krijon një array të nën-arrays që përmbajnë çelësat dhe vlerat e duhura, të cilat rezultojnë në `{ name: "Lydia", age: 22 }` + +

+
+ +--- + +###### 154. Cila është vlera e saj? + +```javascript +const createMember = ({ email, address = {}}) => { + const validEmail = /.+\@.+\..+/.test(email) + if (!validEmail) throw new Error("Valid email pls") + + return { + email, + address: address ? address : null + } +} + +const member = createMember({ email: "my@email.com" }) +console.log(member) +``` + +- A: `{ email: "my@email.com", address: null }` +- B: `{ email: "my@email.com" }` +- C: `{ email: "my@email.com", address: {} }` +- D: `{ email: "my@email.com", address: undefined }` + +
Përgjigja +

+ +#### Përgjigja: C + +Vlera e paracaktuar e `address` është një objekt i zbrazët `{}`. Kur vendosëm variablën `member` të barabartë me objektin që kthehet nga funksioni `createMember`, ne nuk kaluam një vlerë për adresën, që do të thotë se vlera e adresës është objekti i zbrazët parazgjedhur `{}`. Një objekt i zbrazët është një vlerë e vërtetë, që do të thotë se gjendja e `address ? address : null` kushtëzuese kthehet `true`. Vlera e adresës është objekti i zbrazët `{}`. + +

+
+ +--- + +###### 155. Cila është vlera e saj? + +```javascript +let randomValue = { name: "Lydia" } +randomValue = 23 + +if (!typeof randomValue === "string") { + console.log("It's not a string!") +} else { + console.log("Yay it's a string!") +} +``` + +- A: `It's not a string!` +- B: `Yay it's a string!` +- C: `TypeError` +- D: `undefined` + +
Përgjigja +

+ +#### Përgjigja: B + +Kushti brenda deklaratës `if` kontrollon nëse vlera e `!typeof randomValue` është e barabartë me `"string"`. Operatori `!` e shndërron vlerën në një vlerë booleane. Nëse vlera është e vërtetë, vlera e kthyer do të jetë `false`, nëse vlera është e pavërtetë, vlera e kthyer do të jetë `true`. Në këtë rast, vlera e kthyer e `typeof randomValue` është vlera e vërtetë `"number"`, që do të thotë se vlera e `!typeof randomValue` është vlera booleane `false`. + +`!typeof randomValue === "string"` gjithmonë kthen false, pasi në fakt po kontrollojmë `false === "string"`. Pasi që kushtëzimi ktheu `false`, blloku i kodit të deklaratës `else` ekzekutohet, dhe `Yay it's a string!` printohet. + +

+
diff --git a/th-TH/README.md b/th-TH/README.md index 7f27af3b..a5948da5 100644 --- a/th-TH/README.md +++ b/th-TH/README.md @@ -1,33 +1,45 @@ -# รายการคำถามเกี่ยวกับ JavaScript (ขั้นสูง) +
+ +

JavaScript Questions

-ผมโพสต์โจทย์ JavaScript แบบตัวเลือกทุกวันบน [Instagram](https://www.instagram.com/theavocoder) ของผม ซึ่งผมก็ได้นำมาโพสต์ไว้ที่นี่ด้วย +--- + +สวัสดีพวกเราได้โพสคำถามเกี่ยวกับ Javascript เอาไว้ใน [Instagram](https://www.instagram.com/theavocoder) **stories** และก็จะโพสเอาไว้ในนี้ด้วย! +อัปเดตล่าสุด: 24 ธันวาคม -จากขั้นพื้นฐานสู่ขั้นสูง มาทดสอบกันว่าคุณมีความรู้เรื่อง JavaScript ดีขนาดไหน มาทบทวนความรู้ของคุณกันหน่อย หรือเตรียมตัวสำหรับการสัมภาษณ์เกี่ยวกับการเขียนโปรแกรม :muscle: :rocket: ผมอัพเดทคำถามใหม่ๆ ใน repo นี้ทุกๆ สัปดาห์ อัพเดทล่าสุดวันที่ September 27th +คำถามประกอบไปด้วยตั้งแต่ระดับเริ่มต้นถึงขั้นสูง: จุดประสงค์เพื่อวัดความรู้ภาษา Javascript ทบทวนความรู้ เตรียมตัวสำหรับการสัมภาษณ์ :muscle: :rocket: Reposentory นี้มีการ Update อย่างสม่ำเสมอกรณีที่มีคำถามใหม่ๆเข้ามา เราได้ใส่คำตอบเอาไว้ในส่วนที่ซ่อนอยู่ **collapsed sections** ข้างใต้คำถามอย่าลืมคลิกมันนะมันจะขยายออก โชคดีจ้า :heart: -คำตอบจะอยู่ในหมวดที่ซ่อนไว้ใต้คำถาม เพียงแค่คลิก คำตอบก็จะแสดงขึ้นมา ขอให้โชคดีครับ :heart: +สามารถติดต่อผู้พัฒนาได้ที่ 😊
+Instagram || Twitter || LinkedIn || Blog
-หากต้องการได้รับอีเมลล์แจ้งหากผมมีการเพิ่มโจทย์ใหม่ๆ
-✨✉กรุณาลงทะเบียนรับอีเมลล์อัพเดท✉✨ +**_Note_**: เพิ่มเติมสำหรับนักพัฒนาไทยสามารถร่วมพัฒนาโดยการแปลภาษาหรือแก้ไขคำได้นะครับ + +
ลิสต์ภาษาอื่นๆ: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -55,9 +67,9 @@ sayHi(); #### คำตอบ: D -Within the function, we first declare the `name` variable with the `var` keyword. This means that the variable gets hoisted (memory space is set up during the creation phase) with the default value of `undefined`, until we actually get to the line where we define the variable. We haven't defined the variable yet on the line where we try to log the `name` variable, so it still holds the value of `undefined`. +ในฟังก์ชันดังกล่าวได้ทำการประกาศตัวแปร `name` ด้วย `var` คีย์เวิร์ด หมายความว่าตัวแปรได้รับการ Hoisted (คือส่วนของหน่วยความจำจะถูกจองไว้ในขั้นตอน creation phase) ด้วยค่าเริ่มต้น `undefined` จนกว่าจะถึงบรรทัดที่กำหนดค่าให้กับตัวแปร เนื่องจากเราไม่ได้กำหนดค่าให้กับตัวแปรในบรรทัดที่เราแสดงผล ดังนั้นค่าของตัวแปร `name` จึงเป็น `undefined` -Variables with the `let` keyword (and `const`) are hoisted, but unlike `var`, don't get initialized. They are not accessible before the line we declare (initialize) them. This is called the "temporal dead zone". When we try to access the variables before they are declared, JavaScript throws a `ReferenceError`. +ตัวแปรที่ประกาศโดยใช้คีย์เวิร์ด `let` (และ `const`) ถูก Hoisted เช่นกัน แต่มันจะไม่ถูกตั้งค่าเริ่มต้น (initialize) เหมือนกับคีย์เวิร์ด `var` พวกมันไม่สามารถเข้าถึงได้หากยังไม่ถึงบรรทัดที่ถูกประกาศ (initialize) เรียกว่า "temporal dead zone" ดังนั้นเมื่อเราพยายามเข้าถึงตัวแปรก่อนที่จะมีการประกาศ JavaScript จะส่งข้อความ `ReferenceError`

@@ -85,9 +97,9 @@ for (let i = 0; i < 3; i++) { #### คำตอบ: C -Because of the event queue in JavaScript, the `setTimeout` callback function is called _after_ the loop has been executed. Since the variable `i` in the first loop was declared using the `var` keyword, this value was global. During the loop, we incremented the value of `i` by `1` each time, using the unary operator `++`. By the time the `setTimeout` callback function was invoked, `i` was equal to `3` in the first example. +เพราะว่าลำดับเหตุการที่เกิดขึ้นใน Javascript ฟังก์ชัน `setTimeout` ที่เป็น callback ถูกเรียก _หลังจาก_ loop รันเสร็จ เนื่องจากตัวแปร `i` ใน loop แรกถูกประกาศด้วยคีย์เวิร์ด `var` จึงทำให้มันเป็น global scope ระหว่างการวนรอบ loop เป็นการเพิ่มค่า `i` ที่ละ `1` ในแต่ละครั้งด้วย unary operator `++`. ในเวลาที่ `setTimeout` callback ถูกเรียก แต่ว่าค่า `i` มีค่าเท่ากับ `3` แล้วดังตัวอย่างแรก -In the second loop, the variable `i` was declared using the `let` keyword: variables declared with the `let` (and `const`) keyword are block-scoped (a block is anything between `{ }`). During each iteration, `i` will have a new value, and each value is scoped inside the loop. +ใน loop ที่สอง ตัวแปร `i` ถูกประกาศโดยใช้คีย์เวิร์ด `let` : ตัวแปรที่ประกาศด้วยคีย์เวิร์ด `let` (และ `const`) เป็น block-scope (block คืออะไรก็ตามที่อยู่ภายใน `{ }`) ค่า `i` แต่ละค่าจะถูกกำหนดขอบเขตภายใน loop ในเวลาที่ `setTimeout` callback ถูกเรียก ค่า `i` แต่ละค่าจะเป็นค่าเฉพาะของแต่ละ callback `1 2 และ 3` ตามละดับ

@@ -119,11 +131,11 @@ console.log(shape.perimeter()); #### คำตอบ: B -Note that the value of `diameter` is a regular function, whereas the value of `perimeter` is an arrow function. +Note ค่าของ `diameter` เป็น regular function แต่ว่าค่าของ `perimeter` เป็น arrow function. -With arrow functions, the `this` keyword refers to its current surrounding scope, unlike regular functions! This means that when we call `perimeter`, it doesn't refer to the shape object, but to its surrounding scope (window for example). +ด้วย arrow functions คีย์เวิร์ด `this` อ้างอิงไปที่ขอบเขตโดยรอบ (Statis scope หรือ Lexical scope) มันจะไม่เหมือนกับ regular functions! นั้นหมายถึงว่าเมื่อเราเรียก `perimeter` คำว่า `this` มันไม่ได้อ้างอิงไปที่ตัว shape object แต่มันอ้างอิงไปที่ขอบเขตโดยรอบ(ในตัวอย่าง `this` จะอ้างอิงไปที่ window object). -There is no value `radius` on that object, which returns `undefined`. +ไม่มีค่าของ `radius` ที่ window object ดังนั้น `this.radius` จึงมีค่าเป็น `undefined`

@@ -146,9 +158,9 @@ There is no value `radius` on that object, which returns `undefined`. #### คำตอบ: A -The unary plus tries to convert an operand to a number. `true` is `1`, และ `false` is `0`. +เครื่องหมายบวกจะพยายามแปลงตัวถูกดำเนินการเป็นตัวเลข `true` เป็น `1`, และ `false` เป็น `0` -The string `'Lydia'` is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns `false`. +String `'Lydia'` เป็นค่าความจริง สิ่งที่เราถามคือ "ค่าความจริงนี้เป็นเท็จหรือไม่?" (ซึ่งคำตอบก็คือ "ไม่") ค่าจึงเป็น `false`

@@ -178,13 +190,13 @@ const mouse = { #### คำตอบ: A -In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not _type_ them as strings, they are always converted into strings under the hood. +ในภาษา Javascript, ทุกๆ object keys เป็น strings (unless it's a Symbol). แม้ว่าเราไม่ได้กำหนด _type_ ของมันให้เป็น strings, object keys มันจะถูกแปลงเป็น strings หลังบ้านขอภาษา Javscript. -JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket `[` and keeps going until it finds the closing bracket `]`. Only then, it will evaluate the statement. +JavaScript interprets (or unboxes) statements. เมื่อเราใช้ bracket notation, มันจะมองไปที่ opening bracket `[` และมองไปจนถึง closing bracket `]`. หลังจากนั้นมันจะประเมินค่า statement. -`mouse[bird.size]`: First it evaluates `bird.size`, which is `"small"`. `mouse["small"]` returns `true` +`mouse[bird.size]`: การประเมิณลำดับแรก `bird.size`, มีค่าเท่ากับ `"small"`. `mouse["small"]` returns `true` -However, with dot notation, this doesn't happen. `mouse` does not have a key called `bird`, which means that `mouse.bird` is `undefined`. Then, we ask for the `size` using dot notation: `mouse.bird.size`. Since `mouse.bird` is `undefined`, we're actually asking `undefined.size`. This isn't valid, and will throw an error similar to `Cannot read property "size" of undefined`. +อย่างไรก็ตามด้วย dot notation, สิ่งนี้ไม่มีทางเกิดขึ้น. `mouse` ไม่มี key `bird`, ซึ่งหมายความว่า `mouse.bird` มีค่าเป็น `undefined`. เมื่อเราเรียกหา `size` โดยใช้ dot notation: `mouse.bird.size`. เนื่องจาก `mouse.bird` มีค่าเป็น `undefined`, มันเลยเป็นการเรียก `undefined.size`. ซึ่งไม่ valid (isn't valid), และจะมี error แจ้งขึ้นมา `Cannot read property "size" of undefined`.

@@ -214,13 +226,13 @@ console.log(d.greeting); #### คำตอบ: A -In JavaScript, all objects interact by _reference_ when setting them equal to each other. +ในภาษา Javascript, ทุก Object จะ interact โดย _reference_ เมื่อมีการตั้งค่าให้เท่ากัน. -First, variable `c` holds a value to an object. Later, we assign `d` with the same reference that `c` has to the object. +จากคำถามลำดับแรก `c` เก็บค่าที่เป็น object. หลังจากนั้นทำการกำหนดค่า `d` ไปที่ Reference ที่ค่า `c` เนื่องจากค่า `c` เป็น object การกำหนดค่าจึงเป็นการ Reference -When you change one object, you change all of them. +เมื่อมีการเปลี่ยนแปลงค่า object ตัวใดตัวหนึ่งค่าตัวอื่นจึงเปลี่ยนตามไปด้วย

@@ -249,11 +261,11 @@ console.log(b === c); #### คำตอบ: C -`new Number()` is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object. +`new Number()` เป็น built-in function constructor. แม้ว่ามันจะคล้ายกับ number, แต่มันไม่ได้เป็น number จริงๆ: มันมีคุณสมบัติพิเศษมากมายเนื่องจากมันเป็น object -When we use the `==` operator, it only checks whether it has the same _value_. They both have the value of `3`, so it returns `true`. +เมื่อใช้เครื่องหมาย `==` , มันเป็นแค่การตรวจสอบว่าข้อมูลสองค่ามีค่าเท่ากันหรือไม่ _value_. ซึ่งค่าทั้งสองมีค่าเท่ากับ `3`, จึง returns `true`. -However, when we use the `===` operator, both value _and_ type should be the same. It's not: `new Number()` is not a number, it's an **object**. Both return `false.` +อย่างไรก็ตามเมื่อใช้เครื่องหมาย `===` , ทั้งค่าของมัน _และ_ type ของมันควรเหมือนกันจึงจะ return `true`. เนื่องจาก `new Number()` ไม่ใช่ number, มันเป็น **object**. `a === b` _และ_ `b === c` จึง return `false.`

@@ -835,7 +847,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1052,7 +1064,7 @@ console.log(typeof sayHi()); The `sayHi` function returns the returned value of the immediately invoked function (IIFE). This function returned `0`, which is type `"number"`. -FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, และ `symbol`. `"function"` is not a type, since functions are objects, it's of type `"object"`. +FYI: there are only 7 built-in types: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, และ `bigint`. `"function"` is not a type, since functions are objects, it's of type `"object"`.

@@ -3316,7 +3328,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
คำตอบ @@ -3324,7 +3336,7 @@ Promise.resolve(5) #### คำตอบ: C -We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value. If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. +We can pass any type of value we want to `Promise.resolve`, either a promise or a non-promise. The method itself returns a promise with the resolved value (``). If you pass a regular function, it'll be a resolved promise with a regular value. If you pass a promise, it'll be a resolved promise with the resolved value of that passed promise. In this case, we just passed the numerical value `5`. It returns a resolved promise with the value `5`. diff --git a/tr-TR/README-tr_TR.md b/tr-TR/README-tr_TR.md index eb2908df..f1b36c1f 100644 --- a/tr-TR/README-tr_TR.md +++ b/tr-TR/README-tr_TR.md @@ -4,7 +4,7 @@ Temelden ileri düzeye: Javascript'i ne kadar iyi bildiğinizi test edin, bilginizi biraz tazeleyin ya da mülakatanıza hazırlanın! :muscle: :rocket: Repoyu haftalık olarak yeni sorularla güncelliyorum. Son güncelleme: 17 Ağustos -Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanşlar :heart: +Cevaplar, soruların altında gizlenmiştir. Görmek için sadece tıklayın. İyi şanslar :heart: Daha fazla soru eklendikçe eposta almak ister misiniz?
✨✉Eposta bildirimlerine abone olun✉✨ @@ -12,23 +12,28 @@ Daha fazla soru eklendikçe eposta almak ister misiniz?
Mevcut dillerin listesi: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -825,7 +830,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1042,7 +1047,7 @@ console.log(typeof sayHi()); `sayHi` fonksiyonu, anında çalıştırılan fonksiyonun, "immediately invoked function (IIFE)", döndürdüğü değeri döndürür. Bu fonksiyon `0` döndürdü, k, tipi `"number"`'dır. -Bilginize; 7 tane tümleşik tip vardır: `null`, `undefined`, `boolean`, `number`, `string`, `object`, ve `symbol`. Fonksiyonlar nesne olduklarından, `"function"` tip değildir. Fonksiyonun tipi `"object"`'dir. +Bilginize; 7 tane tümleşik tip vardır: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, ve `bigint`. Fonksiyonlar nesne olduklarından, `"function"` tip değildir. Fonksiyonun tipi `"object"`'dir.

diff --git a/ua-UA/README-ua_UA.md b/uk-UA/README.md similarity index 74% rename from ua-UA/README-ua_UA.md rename to uk-UA/README.md index 5b0864b6..6498cc94 100644 --- a/ua-UA/README-ua_UA.md +++ b/uk-UA/README.md @@ -2,27 +2,32 @@ Я публікую щодня завдання з JavaScript в моєму [Instagram](https://www.instagram.com/theavocoder), які також додаю тут! -Від базового до просунутого: перевірте, наскільки добре ви знаєте JavaScript, трохи оновлюйте свої знання або підготуйтеся до інтерв'ю! :muscle: :rocket: Щотижня я доповнюю цей репозиторій новими питаннями. - -Відповіді знаходяться в згорнутої секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: - -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +Від базового до просунутого: перевірте, наскільки добре ви знаєте JavaScript, трохи оновіть свої знання або підготуйтеся до інтерв'ю! :muscle: :rocket: Щотижня я доповнюю цей репозиторій новими питаннями. + +Відповіді знаходяться в згорнутій секції нижче питань. Просто натисни на відповідь, щоб розгорнути. Успіхів! :heart: + +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇻🇳 Tiếng Việt](../vi-VI/README-vi.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -49,7 +54,7 @@ sayHi(); #### Відповідь: D -Усередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення `name`, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. +Всередині функції ми спершу визначаємо змінну `name` за допомогою ключового слова `var`. Це означає, що змінна буде знайдена (область пам'яті під змінну буде виділена під час створення) зі значенням `undefined` за замовчуванням, до тих пір поки виконання коду не дійде до рядка, де визначається змінна. Ми ще не визначили значення `name`, коли намагаємося вивести її в консоль, тому в консолі буде `undefined`. Змінні, визначені за допомогою `let` (і `const`), також знаходяться, але на відміну від `var`, не створюються. Доступ до них неможливий до тих пір, поки не виконається рядок їх визначення (ініціалізації). Це називається "тимчасова мертва зона". Коли ми намагаємося звернутися до змінних до того моменту як вони визначені, JavaScript видає `ReferenceError`. @@ -81,7 +86,7 @@ for (let i = 0; i < 3; i++) { Через черги подій в JavaScript, функція `setTimeout` викликається _після того_ як цикл буде завершено. Так як змінна `i` в першому циклі була визначена за допомогою `var`, вона буде глобальною. У циклі ми кожен раз збільшуємо значення `i` на `1`, використовуючи унарний оператор `++.` До моменту виконання функції `setTimeout` значення `i` дорівнюватиме `3`, як показано в першому прикладі. -У другому циклі змінна `i` визначена за допомогою `let`. Такі змінні (а також `const`) мають блочну область видимості (блок це що завгодно між `{}`). З кожної итерацией `i` матиме нове значення, і кожне значення буде замкнуто в своїй області видимості всередині циклу. +У другому циклі змінна `i` визначена за допомогою `let`. Такі змінні (а також `const`) мають блокову область видимості (блок це що завгодно між `{}`). З кожною ітерацією `i` матиме нове значення, і кожне значення буде замкнуто у своїй області видимості всередині циклу.

@@ -113,9 +118,9 @@ shape.perimeter(); #### Відповідь: B -Зауваж, що `diameter` це звичайна функція, в той час як `perimeter` це функція стрілки. +Зауваж, що `diameter` це звичайна функція, в той час як `perimeter` це стрілкова функція. -У стрілочних функцій значення `this` вказує на навколишню область видимості, на відміну від звичайних функцій! Це означає, що при виклику `perimeter` значення `this` у цій функції вказує не на об'єкт `shape`, а на зовнішню область видимості (наприклад, window). +У стрілкових функцій значення `this` вказує на навколишню область видимості, на відміну від звичайних функцій! Це означає, що при виклику `perimeter` значення `this` у цій функції вказує не на об'єкт `shape`, а на зовнішню область видимості (наприклад, window). У цього об'єкта немає ключа `radius`, тому повертається `undefined`. @@ -178,7 +183,7 @@ JavaScript інтерпретує (або розпаковує) оператор `mouse[bird.size]`: Спершу визначається `bird.size`, що дорівнює `"small"`. `mouse["small"]` повертає `true`. -Але із записом через точку так не відбувається. У `mouse` немає ключа `bird`. Таким чином, `mouse.bird` дорівнює `undefined`. Потім ми запитуємо ключ `size`, використовуючи точкову нотацію: `mouse.bird.size`. Так як `mouse.bird` це `undefined`, ми запитуємо `undefined.size`. Це не є дійсним, і ми отримуємо помилку типу: `Can not read property "size" of undefined`. +Але із записом через крапку так не відбувається. У `mouse` немає ключа `bird`. Таким чином, `mouse.bird` дорівнює `undefined`. Потім ми запитуємо ключ `size`, використовуючи крапкову нотацію: `mouse.bird.size`. Так як `mouse.bird` це `undefined`, ми запитуємо `undefined.size`. Це не є дійсним, тому ми отримуємо помилку типу: `Can not read property "size" of undefined`.

@@ -305,9 +310,9 @@ console.log(greetign); #### Відповідь: A -В консолі виведеться об'єкт, тому що ми тільки що створили порожній об'єкт в глобальному об'єкті! Коли ми замість `greeting` написали `greetign`, інтерпретатор JS насправді виконав `global.greetign = {}` (або `window.greetign = {}` в браузері). +В консолі виведеться об'єкт, тому що ми щойно створили порожній об'єкт в глобальному об'єкті! Коли ми замість `greeting` написали `greetign`, інтерпретатор JS насправді виконав `global.greetign = {}` (або `window.greetign = {}` в браузері). -Потрібно використовувати `"use strict"`, щоб уникнути такої поведінки. Ця запис допоможе бути впевненим в тому, що змінна була визначена перед тим як їй присвоїли значення. +Потрібно використовувати `"use strict"`, щоб уникнути такої поведінки. Цей запис допоможе бути впевненим в тому, що змінна була визначена перед тим як їй присвоїли значення.

@@ -369,7 +374,7 @@ console.log(member.getFullName()); #### Відповідь: A -Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фичу всіх об'єктах, то необхідно використовувати прототипи. В даному випадку, +Не можна додавати властивості конструктору, як звичайному об'єкту. Якщо потрібно додати фічу до всіх об'єктів, то необхідно використовувати прототипи. В даному випадку, ```js Person.prototype.getFullName = function() { @@ -420,17 +425,17 @@ console.log(sarah); ###### 13. Назвіть три фази поширення подій -- A: Мета (Target) > Захоплення (Capturing) > Всплиття (Bubbling) -- B: Всплиття (Bubbling) > Мета (Target) > Захоплення (Capturing) -- C: Мета (Target) > Всплиття (Bubbling) > Захоплення (Capturing) -- D: Захоплення (Capturing) > Мета (Target) > Всплиття (Bubbling) +- A: Мета (Target) > Захоплення (Capturing) > Спливання (Bubbling) +- B: Спливання (Bubbling) > Мета (Target) > Захоплення (Capturing) +- C: Мета (Target) > Спливання (Bubbling) > Захоплення (Capturing) +- D: Захоплення (Capturing) > Мета (Target) > Спливання (Bubbling)
Відповідь

#### Відповідь: D -Під час фази **захоплення** подія поширюється з елементів батьків до елемента мети. Після досягнення **мети** починається фаза **спливання**. +Під час фази **захоплення** подія поширюється від батьківського елемента до елемента мети. Після досягнення **мети** починається фаза **спливання**. @@ -439,7 +444,7 @@ console.log(sarah); --- -###### 14. Все объекты имеют прототипы? +###### 14. Всі об'єкти мають прототипи? - A: Так - B: Ні @@ -476,9 +481,9 @@ sum(1, "2"); #### Відповідь: C -JavaScript це **динамічно тіпізірованна мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. +JavaScript це **динамічно типізована мова**: ми не визначаємо тип змінних. Змінні можуть автоматично бути перетворені з одного типу в інший без нашої участі, що називається _неявним приведенням типів_. **Приведення** це перетворення з одного типу в інший. -У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція усередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо конкатеніровать рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`. +У цьому прикладі, JavaScript конвертувати число `1` в рядок, щоб операція всередині функції мала сенс і повернула значення. Під час складання числа (`1`) і рядки (`'2'`) число перетворюється до рядка. Ми можемо додавати рядки ось так: `"Hello" + "World"`. Таким чином, "`1"` + `"2"` повертає "`12"`.

@@ -511,8 +516,8 @@ console.log(number); **Префіксний** унарний оператор `++`: -1. Інкрементує значення (тепер число дорівнює `1`) -2. Повертає значення (`0`) +1. Інкрементує значення (тепер число дорівнює `2`) +2. Повертає значення (`2`) Результат: `0 2 2`. @@ -545,7 +550,7 @@ getPersonInfo`${person} is ${age} years old`; #### Відповідь: B -При використанні тегованих шаблонних литералов першим аргументом завжди буде масив строкових значень. Залишилися аргументами будуть значення переданих виразів! +При використанні тегованих шаблонних літералів першим аргументом завжди буде масив строкових значень. Решта аргументів будуть значення мати переданих виразів!

@@ -577,9 +582,9 @@ checkAge({ age: 18 }); #### Відповідь: C -В операціях порівняння примітиви порівнюються за їх _значенням_, а об'єкти по _посиланнях_. JavaScript перевіряє, щоб об'єкти вказували на одну і ту ж область пам'яті. +В операціях порівняння примітиви порівнюються за їх _значенням_, а об'єкти за _посиланнями_. JavaScript перевіряє, щоб об'єкти вказували на одну і ту ж область пам'яті. -Порівнянні об'єкти в нашому прикладі не такі: об'єкт, переданий як параметр, вказує на іншу область пам'яті, ніж об'єкти, що використовуються в порівняннях. +Порівнювані об'єкти в нашому прикладі не такі: об'єкт, переданий як параметр, вказує на іншу область пам'яті, ніж об'єкти, що використовуються в порівнянні. Тому `{age: 18} === {age: 18}` і `{age: 18} == {age: 18}` повертають `false`. @@ -660,7 +665,7 @@ const sum = eval("10*10+5"); #### Відповідь: A -`eval` виконує код, переданий у вигляді рядка. Якщо цей вислів (як в даному випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`. +`eval` виконує код, переданий у вигляді рядка. Якщо це рядок (як в такому випадку), то обчислюється вираз. Вираз `10 * 10 + 5` поверне число `105`.

@@ -711,7 +716,7 @@ console.log(num); #### Відповідь: B -За допомогою ключового слова `var`, можна визначати скільки завгодно змінних з одним і тим же ім'ям. Змінна зберігатиме останнім присвоєне значення. +За допомогою ключового слова `var`, можна визначати скільки завгодно змінних з одним і тим же ім'ям. Змінна зберігатиме останнє присвоєне значення. Ви не можете зробити це з `let` або` const`, оскільки вони блочні. @@ -768,7 +773,7 @@ console.log(obj); #### Відповідь: C -Якщо є два ключі з однаковим ім'ям, то ключ буде перезаписан. Його позиція збережеться, але значенням буде встановлено останнім. +Якщо є два ключі з однаковим ім'ям, то ключ буде перезаписаний. Його позиція збережеться, але значенням буде встановлено останнім.

@@ -786,7 +791,7 @@ console.log(obj); #### Відповідь: A -Базовий контекст виконання це глобальний контекст виконання: це те, що є де завгодно в твоєму коді. +Базовий контекст виконання це глобальний контекст виконання: це те, що є де завгодно у твоєму коді.

@@ -828,7 +833,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -904,7 +909,7 @@ baz(); #### Відповідь: B -Ми викликаємо функцію `setTimeout` першої. Тим не менш, вона виводиться в консоль останньої +Ми викликаємо функцію `setTimeout` першою. Тим не менш, вона виводиться в консоль останньою. Це відбувається через те, що в браузерах у нас є не тільки рантайм движок, але і `WebAPI`. `WebAPI` надає нам функцію `setTimeout` і багато інших можливостей. Наприклад, DOM. @@ -1043,9 +1048,9 @@ typeof sayHi(); #### Відповідь: B -Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального вираза_ (IIFE). Результатом є `0` типу `"number"`. +Функція `sayHi` повертає значення, що повертається з _негайно викликаного функціонального виразу_ (IIFE). Результатом є `0` типу `"number"`. -Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, та `symbol`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`. +Для інформації: в JS 7 вбудованих типів: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, та `bigint`. `"Function"` не є окремим типом, тому що функції є об'єктами типу `"object"`.

@@ -1170,7 +1175,7 @@ console.log(numbers); Блок `catch` отримує аргумент `x`. Це не той же `x`, який визначено в якості змінної перед рядком `try`. -Потім ми присвоюємо цього аргументу значення `1` та встановлюємо значення для змінної `y`. Потім виводимо в консоль значення аргументу `x`, що дорівнює `1`. +Потім ми присвоюємо даному аргументу значення `1` та встановлюємо значення для змінної `y`. Потім виводимо в консоль значення аргументу `x`, що дорівнює `1`. За межами блоку `catch` змінна `x` все ще `undefined`, а `y` дорівнює `2`. Коли ми викликаємо` console.log(x)` за межами блоку `catch`, цей виклик повертає `undefined`, а `y` повертає `2`. @@ -1191,7 +1196,7 @@ console.log(numbers); #### Відповідь: A -В JavaScript є тільки примітиви і об'єкти. +В JavaScript є тільки примітиви й об'єкти. Типи примітивів: `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, та `symbol`. @@ -1223,7 +1228,7 @@ console.log(numbers); #### Відповідь: C -`[1, 2]` - початкове значення, з яким инициализируется змінна `acc`. Після першого проходу `acc` дорівнюватиме `[1,2]`, а `cur` буде `[0,1]`. Після конкатенації результат буде `[1, 2, 0, 1]`. +`[1, 2]` - початкове значення, з яким ініціалізується змінна `acc`. Після першого проходу `acc` дорівнюватиме `[1,2]`, а `cur` буде `[0,1]`. Після конкатенації результат буде `[1, 2, 0, 1]`. Потім `acc` дорівнює `[1, 2, 0, 1]`, а cur `[2, 3]`. Після злиття отримаємо `[1, 2, 0, 1, 2, 3]`. @@ -1277,14 +1282,14 @@ setInterval(() => console.log("Hi"), 1000); #### Відповідь: A -Це метод повертає унікальний id. Цей id може бути використаний для очищення інтервалу за допомогою функції `clearInterval()`. +Цей метод повертає унікальний id, який може бути використаний для очищення інтервалу за допомогою функції `clearInterval()`.

--- -###### 43. What does this return? +###### 43. Що повернеться? ```javascript [..."Lydia"]; @@ -1300,7 +1305,113 @@ setInterval(() => console.log("Hi"), 1000); #### Відповідь: A -Рядок є ітеріруемой сутністю. Оператор поширення перетворює кожен символ в окремий елемент. +Рядок є ітерабельною сутністю. Оператор поширення перетворює кожен символ в окремий елемент. + +

+
+ +--- + +###### 44. Що буде в консолі? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
Answer +

+ +#### Відповідь: C + +Звичайні функції не можна зупинити "на півдорозі" після виклику. Однак функція-генератор може зупинитися "на півдорозі", а потім продовжити з того місця, де вона зупинилась. Кожного разу, коли функція-генератор зустрічає ключове слово `yield`, функція видає значення, що вказане після нього. Зауважте, що функція-генератор в цьому випадку не _повертає_ (return) значення, вона _дає_ (yields) значення. + +Спочатку ми ініціалізуємо функцію-генератор з `i` рівним `10`. Ми викликаємо функцію-генератор за допомогою методу `next()`. Коли ми вперше викликаємо функцію генератора, `i` дорівнює `10`. Перше ключове слово `yield`: воно дає значення `i`. Генератор тепер "призупинено", і `10` записується у консоль. + +Потім ми знову викликаємо функцію за допомогою методу `next()`. Виконання коду продовжується там, де зупинилося раніше, все ще з `i` що дорівнює `10`. Тепер функція зустрічає наступне ключове слово `yield` і дає `i * 2`. `i` дорівнює `10`, тож віддається `10 * 2`, що дорівнює `20`. У результаті: `10, 20`. + +

+
+ + +--- + +###### 45. Що повернеться? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
Answer +

+ +#### Відповідь: B + +Коли ми передаємо кілька промісів методу `Promise.race`, він вирішує/відхиляє _перший_ проміс, яки вирішився/відхилився. Методу `setTimeout` ми передаємо таймер: 500 мс для першого промісу (`firstPromise`) та 100 мс для другого промісу (`secondPromise`). Це означає, що `secondPromise` вирішиться першим зі значенням `'two'`. `res` тепер містить значення `'two'`, яке буде зображено у консолі. + +

+
+ +--- + +###### 46. Що буде на виході? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
Answer +

+ +#### Відповідь: D + +Спочатку ми оголошуємо змінну `person` що містить об'єкта, який має властивість `name`. + + + +Потім ми оголошуємо змінну `members`. Ми встановлюємо перший елемент масиву рівним значенню змінної `person`. Об'єкти взаємодіють за допомогою _посилання_, коли їх встановлюють рівними один одному. Коли ви призначаєте посилання з однієї змінної на іншу, ви робите _копію_ цього посилання. (зверніть увагу, що вони не мають _однакового_ посилання!) + + + +Далі ми встановлюємо змінну `person` рівною `null`. + + + +Ми лише змінюємо значення змінної `person`, а не перший елемент у масиві, оскільки цей елемент має інше (скопійоване) посилання на об’єкт.Перший елемент у `members` все ще містить своє посилання на вихідний об’єкт. Коли ми виводимо у консоль масив `members`, перший елемент усе ще містить значення об'єкта, який і показується у консолі.

diff --git a/vi-VI/README-vi.md b/vi-VI/README-vi.md index 473a540c..f8ab661d 100644 --- a/vi-VI/README-vi.md +++ b/vi-VI/README-vi.md @@ -7,23 +7,28 @@ Các câu hỏi sẽ từ cơ bản đến nâng cao: kiểm tra trình độ Ja Các đáp án được đặt dưới mỗi câu hỏi, hãy click để tham khảo chúng. Chúc may mắn :heart: Danh sách các ngôn ngữ khác: -* [English](../en-EN/README.md) -* [العربية](../ar-AR/README_AR.md) -* [اللغة العامية - Egyptian Arabic](../ar-EG/README_ar-EG.md) -* [Bosanski](../bs-BS/README-bs_BS.md) -* [Deutsch](../de-DE/README.md) -* [Español](../es-ES/README-ES.md) -* [Français](../fr-FR/README_fr-FR.md) -* [日本語](../ja-JA/README-ja_JA.md) -* [한국어](../ko-KR/README-ko_KR.md) -* [Nederlands](./nl-NL/README.md) -* [Português Brasil](../pt-BR/README_pt_BR.md) -* [Русский](../ru-RU/README.md) -* [Українська мова](../ua-UA/README-ua_UA.md) -* [Tiếng Việt](../vi-VI/README-vi.md) -* [中文版本](../zh-CN/README-zh_CN.md) -* [Türkçe](../tr-TR/README-tr_TR.md) -* [ไทย](../th-TH/README-th_TH.md) +- [🇸🇦 العربية](../ar-AR/README_AR.md) +- [🇪🇬 اللغة العامية](../ar-EG/README_ar-EG.md) +- [🇧🇦 Bosanski](../bs-BS/README-bs_BS.md) +- [🇩🇪 Deutsch](../de-DE/README.md) +- [🇬🇧 English](../README.md) +- [🇪🇸 Español](../es-ES/README-ES.md) +- [🇫🇷 Français](../fr-FR/README_fr-FR.md) +- [🇮🇩 Indonesia](../id-ID/README.md) +- [🇮🇹 Italiano](../it-IT/README.md) +- [🇯🇵 日本語](../ja-JA/README-ja_JA.md) +- [🇰🇷 한국어](../ko-KR/README-ko_KR.md) +- [🇳🇱 Nederlands](../nl-NL/README.md) +- [🇵🇱 Polski](../pl-PL/README.md) +- [🇧🇷 Português Brasil](../pt-BR/README_pt_BR.md) +- [🇷o Română](../ro-RO/README.ro.md) +- [🇷🇺 Русский](../ru-RU/README.md) +- [🇽🇰 Shqip](../sq-KS/README_sq_KS.md) +- [🇹🇭 ไทย](../th-TH/README-th_TH.md) +- [🇹🇷 Türkçe](../tr-TR/README-tr_TR.md) +- [🇺🇦 Українська мова](../uk-UA/README.md) +- [🇨🇳 简体中文](../zh-CN/README-zh_CN.md) +- [🇹🇼 繁體中文](../zh-TW/README_zh-TW.md) --- @@ -336,7 +341,7 @@ bark.animal = "dog"; #### Đáp án: A -Điều này là có thể với Javascript, bởi vì `function` cũng chỉ là `object` mà thôi! (Mọi primitive types đều là object) +Điều này là có thể với Javascript, bởi vì `function` cũng chỉ là `object` mà thôi! (Các kiểu dữ liệu khác ngoài các kiểu nguyên thủy được gọi là kiểu dữ liệu tham chiếu) Function là một object đặc biệt. Phần code mà bạn viết không phải là function thực tế đâu. Function ở đây chính là một object với các thuộc tính. Và các thuộc tính này có thể gọi được. @@ -831,7 +836,7 @@ String.prototype.giveLydiaPizza = () => { const name = "Lydia"; -name.giveLydiaPizza(); +console.log(name.giveLydiaPizza()) ``` - A: `"Just give Lydia pizza already!"` @@ -1048,7 +1053,7 @@ typeof sayHi(); `sayHi` function trả về giá trị của một _hàm gọi ngay lập tức_ (immediately invoked function - IIFE). Function này trả về `0`, kiểu dữ liệu `"number"`. -FYI: chỉ có 7 kiểu dữ liệu built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object`, and `symbol`. `"function"` không phải là một kiểu, mà là objects, kiểu dữ liệu là `"object"`. +FYI: chỉ có 7 kiểu dữ liệu built-in: `null`, `undefined`, `boolean`, `number`, `string`, `object`, `symbol`, and `bigint`. `"function"` không phải là một kiểu, mà là objects, kiểu dữ liệu là `"object"`.

@@ -3313,7 +3318,7 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
Đáp án @@ -4706,3 +4711,372 @@ Mặc định ta không thể duyệt qua được object. Trừ phi nó đượ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+
diff --git a/zh-CN/README-zh_CN.md b/zh-CN/README-zh_CN.md index 5869c0e2..52ca1ee0 100644 --- a/zh-CN/README-zh_CN.md +++ b/zh-CN/README-zh_CN.md @@ -30,7 +30,7 @@ sayHi()
答案

-#### 答案: D +#### 答案:D 在函数内部,我们首先通过 `var` 关键字声明了 `name` 变量。这意味着变量被提升了(内存空间在创建阶段就被设置好了),直到程序运行到定义变量位置之前默认值都是 `undefined`。因为当我们打印 `name` 变量时还没有执行到定义变量的位置,因此变量的值保持为 `undefined`。 @@ -60,7 +60,7 @@ for (let i = 0; i < 3; i++) {

答案

-#### 答案: C +#### 答案:C 由于 JavaScript 的事件循环,`setTimeout` 回调会在*遍历结束后*才执行。因为在第一个遍历中遍历 `i` 是通过 `var` 关键字声明的,所以这个值是全局作用域下的。在遍历过程中,我们通过一元操作符 `++` 来每次递增 `i` 的值。当 `setTimeout` 回调执行的时候,`i` 的值等于 3。 @@ -94,7 +94,7 @@ shape.perimeter()

答案

-#### 答案: B +#### 答案:B 注意 `diameter` 的值是一个常规函数,但是 `perimeter` 的值是一个箭头函数。 @@ -121,7 +121,7 @@ shape.perimeter()

答案

-#### 答案: A +#### 答案:A 一元操作符加号尝试将 bool 转为 number。`true` 转换为 number 的话为 `1`,`false` 为 `0`。 @@ -153,7 +153,7 @@ const mouse = {

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,所有对象的 keys 都是字符串(除非对象是 Symbol)。尽管我们可能不会定义它们为字符串,但它们在底层总会被转换为字符串。 @@ -188,7 +188,7 @@ console.log(d.greeting)

答案

-#### 答案: A +#### 答案:A 在 JavaScript 中,当设置两个对象彼此相等时,它们会通过*引用*进行交互。 @@ -223,7 +223,7 @@ console.log(b === c)

答案

-#### 答案: C +#### 答案:C `new Number()` 是一个内建的函数构造器。虽然它看着像是一个 number,但它实际上并不是一个真实的 number:它有一堆额外的功能并且它是一个对象。 @@ -262,7 +262,7 @@ freddie.colorChange('orange')

答案

-#### 答案: D +#### 答案:D `colorChange` 是一个静态方法。静态方法被设计为只能被创建它们的构造器使用(也就是 `Chameleon`),并且不能传递给实例。因为 `freddie` 是一个实例,静态方法不能被实例使用,因此抛出了 `TypeError` 错误。 @@ -286,9 +286,9 @@ console.log(greetign)

答案

-#### 答案: A +#### 答案:A -代码打印出了一个对象,这是因为我们在全局对象上创建了一个空对象!当我们将 `greeting` 写错成 `greetign` 时,JS 解释器实际在上浏览器中将它视为 `global.greetign = {}` (或者 `window.greetign = {}`)。 +代码打印出了一个对象,这是因为我们在全局对象上创建了一个空对象!当我们将 `greeting` 写错成 `greetign` 时,JS 解释器实际在上浏览器中将它视为 `global.greetign = {}`(或者 `window.greetign = {}`)。 为了避免这个为题,我们可以使用 `"use strict"。这能确保当你声明变量时必须赋值。 @@ -307,7 +307,7 @@ function bark() { bark.animal = 'dog' ``` -- A: 正常运行! +- A: 正常运行! - B: `SyntaxError`. 你不能通过这种方式给函数增加属性。 - C: `undefined` - D: `ReferenceError` @@ -315,7 +315,7 @@ bark.animal = 'dog'

答案

-#### 答案: A +#### 答案:A 这在 JavaScript 中是可以的,因为函数是对象!(除了基本类型之外其他都是对象) @@ -350,7 +350,7 @@ console.log(member.getFullName());

答案

-#### 答案: A +#### 答案:A 你不能像常规对象那样,给构造函数添加属性。如果你想一次性给所有实例添加特性,你应该使用原型。因此本例中,使用如下方式: @@ -390,7 +390,7 @@ console.log(sarah)

答案

-#### 答案: A +#### 答案:A 对于 `sarah`,我们没有使用 `new` 关键字。当使用 `new` 时,`this` 引用我们创建的空对象。当未使用 `new` 时,`this` 引用的是**全局对象**(global object)。 @@ -411,7 +411,7 @@ console.log(sarah)

答案

-#### 答案: D +#### 答案:D 在**捕获**(capturing)阶段中,事件从祖先元素向下传播到目标元素。当事件达到**目标**(target)元素后,**冒泡**(bubbling)才开始。 @@ -430,7 +430,7 @@ console.log(sarah)

答案

-#### 答案: B +#### 答案:B 除了**基本对象**(base object),所有对象都有原型。基本对象可以访问一些方法和属性,比如 `.toString`。这就是为什么你可以使用内置的 JavaScript 方法!所有这些方法在原型上都是可用的。虽然 JavaScript 不能直接在对象上找到这些方法,但 JavaScript 会沿着原型链找到它们,以便于你使用。 @@ -457,7 +457,7 @@ sum(1, '2')

答案

-#### 答案: C +#### 答案:C JavaScript 是一种**动态类型语言**:我们不指定某些变量的类型。值可以在你不知道的情况下自动转换成另一种类型,这种类型称为**隐式类型转换**(implicit type coercion)。**Coercion** 是指将一种类型转换为另一种类型。 @@ -485,7 +485,7 @@ console.log(number)

答案

-#### 答案: C +#### 答案:C 一元**后自增**运算符 `++`: @@ -526,7 +526,7 @@ getPersonInfo`${person} is ${age} years old`

答案

-#### 答案: B +#### 答案:B 如果使用标记模板字面量,第一个参数的值总是包含字符串的数组。其余的参数获取的是传递的表达式的值! @@ -558,7 +558,7 @@ checkAge({ age: 18 })

答案

-#### 答案: C +#### 答案:C 在测试相等性时,基本类型通过它们的值(value)进行比较,而对象通过它们的引用(reference)进行比较。JavaScript 检查对象是否具有对内存中相同位置的引用。 @@ -589,7 +589,7 @@ getAge(21)

答案

-#### 答案: C +#### 答案:C 扩展运算符(`...args`)会返回实参组成的数组。而数组是对象,因此 `typeof args` 返回 `"object"`。 @@ -618,7 +618,7 @@ getAge()

答案

-#### 答案: C +#### 答案:C 使用 `"use strict"`,你可以确保不会意外地声明全局变量。我们从来没有声明变量 `age`,因为我们使用 `"use strict"`,它将抛出一个引用错误。如果我们不使用 `"use strict"`,它就会工作,因为属性 `age` 会被添加到全局对象中了。 @@ -641,7 +641,7 @@ const sum = eval('10*10+5')

答案

-#### 答案: A +#### 答案:A 代码以字符串形式传递进来,`eval` 对其求值。如果它是一个表达式,就像本例中那样,它对表达式求值。表达式是 `10 * 10 + 5`。这将返回数字 `105`。 @@ -664,7 +664,7 @@ sessionStorage.setItem('cool_secret', 123)

答案

-#### 答案: B +#### 答案:B 关闭 **tab 标签页** 后,`sessionStorage` 存储的数据才会删除。 @@ -692,7 +692,7 @@ console.log(num)

答案

-#### 答案: B +#### 答案:B 使用 `var` 关键字,你可以用相同的名称声明多个变量。然后变量将保存最新的值。 @@ -723,7 +723,7 @@ set.has(1)

答案

-#### 答案: C +#### 答案:C 所有对象的键(不包括 Symbol)在底层都是字符串,即使你自己没有将其作为字符串输入。这就是为什么 `obj.hasOwnProperty('1')` 也返回 `true`。 @@ -749,7 +749,7 @@ console.log(obj)

答案

-#### 答案: C +#### 答案:C 如果你有两个名称相同的键,则键会被替换掉。它仍然位于第一个键出现的位置,但是值是最后出现那个键的值。 @@ -767,7 +767,7 @@ console.log(obj)

答案

-#### 答案: A +#### 答案:A 基本执行上下文是全局执行上下文:它是代码中随处可访问的内容。 @@ -793,7 +793,7 @@ for (let i = 1; i < 5; i++) {

答案

-#### 答案: C +#### 答案:C 如果某个条件返回 `true`,则 `continue` 语句跳过本次迭代。 @@ -822,9 +822,9 @@ name.giveLydiaPizza()

答案

-#### 答案: A +#### 答案:A -`String` 是内置的构造函数,我们可以向它添加属性。我只是在它的原型中添加了一个方法。基本类型字符串被自动转换为字符串对象,由字符串原型函数生成。因此,所有 string(string 对象)都可以访问该方法! +`String` 是内置的构造函数,我们可以向它添加属性。我只是在它的原型中添加了一个方法。基本类型字符串被自动转换为字符串对象,由字符串原型函数生成。因此,所有 string(string 对象) 都可以访问该方法!

@@ -852,7 +852,7 @@ console.log(a[b])
答案

-#### 答案: B +#### 答案:B 对象的键被自动转换为字符串。我们试图将一个对象 `b` 设置为对象 `a` 的键,且相应的值为 `123`。 @@ -885,13 +885,13 @@ baz()

答案

-#### 答案: B +#### 答案:B 我们有一个 `setTimeout` 函数,并首先调用它。然而,它是最后打印日志的。 这是因为在浏览器中,我们不仅有运行时引擎,还有一个叫做 `WebAPI` 的东西。`WebAPI` 提供了 `setTimeout` 函数,也包含其他的,例如 DOM。 -将 _callback_ 推送到 WebAPI 后,`setTimeout` 函数本身(但不是回调!)将从栈中弹出。 +将 _callback_ 推送到 WebAPI 后,`setTimeout` 函数本身 (但不是回调!) 将从栈中弹出。 @@ -899,7 +899,7 @@ baz() -`foo` 从栈中弹出,`baz` 被调用. 打印 `"Third"`。 +`foo` 从栈中弹出,`baz` 被调用。打印 `"Third"`。 @@ -918,7 +918,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名 --- -###### 31. 当点击按钮时,event.target是什么? +###### 31. 当点击按钮时,event.target 是什么? ```html

@@ -938,7 +938,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名
答案

-#### 答案: C +#### 答案:C 导致事件的最深嵌套的元素是事件的 target。你可以通过 `event.stopPropagation` 来停止冒泡。 @@ -965,7 +965,7 @@ WebAPI 不能随时向栈内添加内容。相反,它将回调函数推到名

答案

-#### 答案: A +#### 答案:A 如果我们点击 `p`,我们会看到两个日志:`p` 和 `div`。在事件传播期间,有三个阶段:捕获、目标和冒泡。默认情况下,事件处理程序在冒泡阶段执行(除非将 `useCapture` 设置为 `true`)。它从嵌套最深的元素向外传播。 @@ -995,7 +995,7 @@ sayHi.bind(person, 21)

答案

-#### 答案: D +#### 答案:D 使用这两种方法,我们都可以传递我们希望 `this` 关键字引用的对象。但是,`.call` 是**立即执行**的。 @@ -1024,11 +1024,11 @@ typeof sayHi()

答案

-#### 答案: B +#### 答案:B -`sayHi` 方法返回的是立即执行函数(IIFE)的返回值.此立即执行函数的返回值是 `0`, 类型是 `number` +`sayHi` 方法返回的是立即执行函数 (IIFE) 的返回值。此立即执行函数的返回值是 `0`,类型是 `number` -参考:只有7种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object` 和 `symbol`。 ``function`` 不是一种类型,函数是对象,它的类型是``object``。 +参考:只有 7 种内置类型:`null`,`undefined`,`boolean`,`number`,`string`,`object`, `symbol` 和 `bigint`。``function`` 不是一种类型,函数是对象,它的类型是``object``。

@@ -1054,20 +1054,22 @@ undefined
答案

-#### 答案: A +#### 答案:A -只有 6 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: +只有 8 种 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy) 值: - `undefined` - `null` - `NaN` -- `0` -- `''` (empty string) - `false` +- `''` (empty string) +- `0` +- `-0` +- `0n` (BigInt(0)) -`Function` 构造函数, 比如 `new Number` 和 `new Boolean`,是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。 +`Function` 构造函数,比如 `new Number` 和 `new Boolean`,是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。

@@ -1088,7 +1090,7 @@ console.log(typeof typeof 1)
答案

-#### 答案: B +#### 答案:B `typeof 1` 返回 `"number"`。 `typeof "number"` 返回 `"string"`。 @@ -1114,9 +1116,9 @@ console.log(numbers)

答案

-#### 答案: C +#### 答案:C -当你为数组设置超过数组长度的值的时候, JavaScript 会创建名为 "empty slots" 的东西。它们的值实际上是 `undefined`。你会看到以下场景: +当你为数组设置超过数组长度的值的时候,JavaScript 会创建名为 "empty slots" 的东西。它们的值实际上是 `undefined`。你会看到以下场景: `[1, 2, 3, 7 x empty, 11]` @@ -1151,13 +1153,13 @@ console.log(numbers)

答案

-#### 答案: A +#### 答案:A -`catch` 代码块接收参数 `x`。当我们传递参数时,这与之前定义的变量 `x` 不同 。这个 `x` 是属于 `catch` 块级作用域的。 +`catch` 代码块接收参数 `x`。当我们传递参数时,这与之前定义的变量 `x` 不同。这个 `x` 是属于 `catch` 块级作用域的。 然后,我们将块级作用域中的变量赋值为 `1`,同时也设置了变量 `y` 的值。现在,我们打印块级作用域中的变量 `x`,值为 `1`。 -`catch` 块之外的变量 `x` 的值仍为 `undefined`, `y` 的值为 `2`。当我们在 `catch` 块之外执行 `console.log(x)` 时,返回 `undefined`,`y` 返回 `2`。 +`catch` 块之外的变量 `x` 的值仍为 `undefined`,`y` 的值为 `2`。当我们在 `catch` 块之外执行 `console.log(x)` 时,返回 `undefined`,`y` 返回 `2`。

@@ -1174,7 +1176,7 @@ console.log(numbers)
答案

-#### 答案: A +#### 答案:A JavaScript 只有基本类型和对象。 @@ -1204,10 +1206,10 @@ JavaScript 只有基本类型和对象。

答案

-#### 答案: C +#### 答案:C -`[1, 2]`是初始值。初始值将会作为首次调用时第一个参数 `acc` 的值。在第一次执行时, `acc` 的值是 `[1, 2]`, `cur` 的值是 `[0, 1]`。合并它们,结果为 `[1, 2, 0, 1]`。 -第二次执行, `acc` 的值是 `[1, 2, 0, 1]`, `cur` 的值是 `[2, 3]`。合并它们,最终结果为 `[1, 2, 0, 1, 2, 3]` +`[1, 2]`是初始值。初始值将会作为首次调用时第一个参数 `acc` 的值。在第一次执行时,`acc` 的值是 `[1, 2]`,`cur` 的值是 `[0, 1]`。合并它们,结果为 `[1, 2, 0, 1]`。 +第二次执行,`acc` 的值是 `[1, 2, 0, 1]`,`cur` 的值是 `[2, 3]`。合并它们,最终结果为 `[1, 2, 0, 1, 2, 3]`

@@ -1230,13 +1232,13 @@ JavaScript 只有基本类型和对象。
答案

-#### 答案: B +#### 答案:B -`null` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。 `!null` 的值是 `true`。 `!true` 的值是 `false`。 +`null` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。`!null` 的值是 `true`。`!true` 的值是 `false`。 -`""` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。 `!""` 的值是 `true`。 `!true` 的值是 `false`。 +`""` 是 [falsy](https://developer.mozilla.org/zh-CN/docs/Glossary/Falsy)。`!""` 的值是 `true`。`!true` 的值是 `false`。 -`1` 是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。 `!1` 的值是 `false`。 `!false` 的值是 `true`。 +`1` 是 [truthy](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)。`!1` 的值是 `false`。`!false` 的值是 `true`。

@@ -1249,7 +1251,7 @@ JavaScript 只有基本类型和对象。 setInterval(() => console.log('Hi'), 1000) ``` -- A: 一个唯一的id +- A: 一个唯一的 id - B: 该方法指定的毫秒数 - C: 传递的函数 - D: `undefined` @@ -1257,7 +1259,7 @@ setInterval(() => console.log('Hi'), 1000)
答案

-#### 答案: A +#### 答案:A `setInterval` 返回一个唯一的 id。此 id 可被用于 `clearInterval` 函数来取消定时。 @@ -1280,7 +1282,7 @@ setInterval(() => console.log('Hi'), 1000)

答案

-#### 答案: A +#### 答案:A string 类型是可迭代的。扩展运算符将迭代的每个字符映射成一个元素。 @@ -1289,7 +1291,7 @@ string 类型是可迭代的。扩展运算符将迭代的每个字符映射成 --- -###### 44. 输出是什么? +###### 44. 输出是什么? ```javascript function* generator(i) { @@ -1311,9 +1313,9 @@ console.log(gen.next().value);

答案

-#### 答案: C +#### 答案:C -一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途“停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ )值,而是 _生成_ (_yield_)值。 +一般的函数在执行之后是不能中途停下的。但是,生成器函数却可以中途“停下”,之后可以再从停下的地方继续。当生成器遇到`yield`关键字的时候,会生成`yield`后面的值。注意,生成器在这种情况下不 _返回_ (_return_ ) 值,而是 _生成_ (_yield_) 值。 首先,我们用`10`作为参数`i`来初始化生成器函数。然后使用`next()`方法一步步执行生成器。第一次执行生成器的时候,`i`的值为`10`,遇到第一个`yield`关键字,它要生成`i`的值。此时,生成器“暂停”,生成了`10`。 @@ -1323,7 +1325,7 @@ console.log(gen.next().value);

-###### 45. 返回值是什么? +###### 45. 返回值是什么? ```javascript const firstPromise = new Promise((res, rej) => { @@ -1345,16 +1347,16 @@ Promise.race([firstPromise, secondPromise]).then(res => console.log(res));
答案

-#### 答案: B +#### 答案:B -当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了500ms和100ms的定时器。这意味着`secondPromise`会首先解析出字符串`two`。那么此时`res`参数即为`two`,是为输出结果。 +当我们向`Promise.race`方法中传入多个`Promise`时,会进行 _优先_ 解析。在这个例子中,我们用`setTimeout`给`firstPromise`和`secondPromise`分别设定了 500ms 和 100ms 的定时器。这意味着`secondPromise`会首先解析出字符串`two`。那么此时`res`参数即为`two`,是为输出结果。

--- -###### 46. 输出是什么? +###### 46. 输出是什么? ```javascript let person = { name: "Lydia" }; @@ -1372,14 +1374,14 @@ console.log(members);
答案

-#### 答案: D +#### 答案:D 首先我们声明了一个拥有`name`属性的对象 `person`。 -然后我们又声明了一个变量`members`. 将首个元素赋值为变量`person`。 当设置两个对象彼此相等时,它们会通过 _引用_ 进行交互。但是当你将引用从一个变量分配至另一个变量时,其实只是执行了一个 _复制_ 操作。(注意一点,他们的引用 _并不相同_!) +然后我们又声明了一个变量`members`. 将首个元素赋值为变量`person`。当设置两个对象彼此相等时,它们会通过 _引用_ 进行交互。但是当你将引用从一个变量分配至另一个变量时,其实只是执行了一个 _复制_ 操作。(注意一点,他们的引用 _并不相同_!) @@ -1387,14 +1389,14 @@ console.log(members); -我们没有修改数组第一个元素的值,而只是修改了变量`person`的值,因为元素(复制而来)的引用与`person`不同。`members`的第一个元素仍然保持着对原始对象的引用。当我们输出`members`数组时,第一个元素会将引用的对象打印出来。 +我们没有修改数组第一个元素的值,而只是修改了变量`person`的值,因为元素(复制而来)的引用与`person`不同。`members`的第一个元素仍然保持着对原始对象的引用。当我们输出`members`数组时,第一个元素会将引用的对象打印出来。

--- -###### 47. 输出是什么? +###### 47. 输出是什么? ```javascript const person = { @@ -1415,16 +1417,16 @@ for (const item in person) {
答案

-#### 答案: B +#### 答案:B -在`for-in`循环中,我们可以通过对象的key来进行迭代,也就是这里的`name`和`age`。在底层,对象的key都是字符串(如果他们不是Symbol的话)。在每次循环中,我们将`item`设定为当前遍历到的key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。 +在`for-in`循环中,我们可以通过对象的 key 来进行迭代,也就是这里的`name`和`age`。在底层,对象的 key 都是字符串(如果他们不是 Symbol 的话)。在每次循环中,我们将`item`设定为当前遍历到的 key.所以一开始,`item`是`name`,之后 `item`输出的则是`age`。

--- -###### 48. 输出是什么? +###### 48. 输出是什么? ```javascript console.log(3 + 4 + "5"); @@ -1438,20 +1440,20 @@ console.log(3 + 4 + "5");
答案

-#### 答案: B +#### 答案:B 当所有运算符的 _优先级_ 相同时,计算表达式需要确定运算符的结合顺序,即从右到左还是从左往右。在这个例子中,我们只有一类运算符`+`,对于加法来说,结合顺序就是从左到右。 `3 + 4`首先计算,得到数字`7`. -由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript将`7`转换成了字符串,可以参考问题15.我们可以用`+`号把两个字符串连接起来。 `"7" + "5"` 就得到了`"75"`. +由于类型的强制转换,`7 + '5'`的结果是`"75"`. JavaScript 将`7`转换成了字符串,可以参考问题 15.我们可以用`+`号把两个字符串连接起来。`"7" + "5"` 就得到了`"75"`.

--- -###### 49. `num`的值是什么? +###### 49. `num`的值是什么? ```javascript const num = parseInt("7*6", 10); @@ -1465,9 +1467,9 @@ const num = parseInt("7*6", 10);
答案

-#### 答案: C +#### 答案:C -只返回了字符串中第一个字母. 设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制: 十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法. 一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 +只返回了字符串中第一个字母。设定了 _进制_ 后 (也就是第二个参数,指定需要解析的数字是什么进制:十进制、十六机制、八进制、二进制等等……),`parseInt` 检查字符串中的字符是否合法。一旦遇到一个在指定进制中不合法的字符后,立即停止解析并且忽略后面所有的字符。 `*`就是不合法的数字字符。所以只解析到`"7"`,并将其解析为十进制的`7`. `num`的值即为`7`. @@ -1476,7 +1478,7 @@ const num = parseInt("7*6", 10); --- -###### 50. 输出是什么? +###### 50. 输出是什么? ```javascript [1, 2, 3].map(num => { @@ -1493,9 +1495,9 @@ const num = parseInt("7*6", 10);

答案

-#### 答案: C +#### 答案:C -对数组进行映射的时候,`num`就是当前循环到的元素. 在这个例子中,所有的映射都是number类型,所以if中的判断`typeof num === "number"`结果都是`true`.map函数创建了新数组并且将函数的返回值插入数组。 +对数组进行映射的时候,`num`就是当前循环到的元素。在这个例子中,所有的映射都是 number 类型,所以 if 中的判断`typeof num === "number"`结果都是`true`.map 函数创建了新数组并且将函数的返回值插入数组。 但是,没有任何值返回。当函数没有返回任何值时,即默认返回`undefined`.对数组中的每一个元素来说,函数块都得到了这个返回值,所以结果中每一个元素都是`undefined`. @@ -1504,7 +1506,7 @@ const num = parseInt("7*6", 10); --- -###### 51. 输出的是什么? +###### 51. 输出的是什么? ```javascript function getInfo(member, year) { @@ -1528,20 +1530,20 @@ console.log(person, birthYear);

答案

-#### 答案: A +#### 答案:A -普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_ 。(可以参考问题46) +普通参数都是 _值_ 传递的,而对象则不同,是 _引用_ 传递。所以说,`birthYear`是值传递,因为他是个字符串而不是对象。当我们对参数进行值传递时,会创建一份该值的 _复制_。(可以参考问题 46) 变量`birthYear`有一个对`"1997"`的引用,而传入的参数也有一个对`"1997"`的引用,但二者的引用并不相同。当我们通过给 `year`赋值`"1998"`来更新`year`的值的时候我们只是更新了`year`(的引用)。此时`birthYear`仍然是`"1997"`. -而`person`是个对象。参数`member`引用与之 _相同的_ 对象。当我们修改`member`所引用对象的属性时,`person`的相应属性也被修改了,因为他们引用了相同的对象. `person`的 `name`属性也变成了 `"Lydia"`. +而`person`是个对象。参数`member`引用与之 _相同的_ 对象。当我们修改`member`所引用对象的属性时,`person`的相应属性也被修改了,因为他们引用了相同的对象。`person`的 `name`属性也变成了 `"Lydia"`.

--- -###### 52. 输出是什么? +###### 52. 输出是什么? ```javascript function greeting() { @@ -1568,9 +1570,9 @@ sayHi();
答案

-#### 答案: D +#### 答案:D -通过`throw`语句,我么可以创建自定义错误。 而通过它,我们可以抛出异常。异常可以是一个字符串, 一个 数字, 一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. +通过`throw`语句,我么可以创建自定义错误。而通过它,我们可以抛出异常。异常可以是一个字符串,一个 数字,一个 布尔类型 或者是一个 对象。在本例中,我们的异常是字符串`'Hello world'`. 通过 `catch`语句,我们可以设定当`try`语句块中抛出异常后应该做什么处理。在本例中抛出的异常是字符串`'Hello world'`. `e`就是这个字符串,因此被输出。最终结果就是`'Oh an error: Hello world'`. @@ -1579,7 +1581,7 @@ sayHi(); --- -###### 53. 输出是什么? +###### 53. 输出是什么? ```javascript function Car() { @@ -1599,7 +1601,7 @@ console.log(myCar.make);

答案

-#### 答案: B +#### 答案:B 返回属性的时候,属性的值等于 _返回的_ 值,而不是构造函数中设定的值。我们返回了字符串 `"Maserati"`,所以 `myCar.make`等于`"Maserati"`. @@ -1608,7 +1610,7 @@ console.log(myCar.make); --- -###### 54. 输出是什么? +###### 54. 输出是什么? ```javascript (() => { @@ -1627,27 +1629,27 @@ console.log(typeof y);

答案

-#### 答案: A +#### 答案:A -`let x = y = 10;` 是下面这个表达式的缩写: +`let x = y = 10;` 是下面这个表达式的缩写: ```javascript y = 10; let x = y; ``` -我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象(浏览器里的`window`, Nodejs里的`global`)。在浏览器中, `window.y`等于`10`. +我们设定`y`等于`10`时,我们实际上增加了一个属性`y`给全局对象 (浏览器里的`window`, Nodejs 里的`global`)。在浏览器中,`window.y`等于`10`. -然后我们声明了变量`x`等于`y`,也是`10`.但变量是使用 `let`声明的,它只作用于 _块级作用域_, 仅在声明它的块中有效;就是案例中的立即调用表达式(IIFE)。使用`typeof`操作符时, 操作值 `x`没有被定义:因为我们在`x`声明块的外部,无法调用它。这就意味着`x`未定义。未分配或是未声明的变量类型为`"undefined"`. `console.log(typeof x)`返回`"undefined"`. +然后我们声明了变量`x`等于`y`,也是`10`.但变量是使用 `let`声明的,它只作用于 _块级作用域_,仅在声明它的块中有效;就是案例中的立即调用表达式 (IIFE)。使用`typeof`操作符时,操作值 `x`没有被定义:因为我们在`x`声明块的外部,无法调用它。这就意味着`x`未定义。未分配或是未声明的变量类型为`"undefined"`. `console.log(typeof x)`返回`"undefined"`. -而我们创建了全局变量`y`,并且设定`y`等于`10`.这个值在我们的代码各处都访问的到。 `y`已经被定义了,而且有一个`"number"`类型的值。 `console.log(typeof y)`返回`"number"`. +而我们创建了全局变量`y`,并且设定`y`等于`10`.这个值在我们的代码各处都访问的到。`y`已经被定义了,而且有一个`"number"`类型的值。`console.log(typeof y)`返回`"number"`.

--- -###### 55. 输出是什么? +###### 55. 输出是什么? ```javascript class Dog { @@ -1677,9 +1679,9 @@ pet.bark();
答案

-#### 答案: A +#### 答案:A -我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用, 然而后面的代码还在调用它。 +我们可以用`delete`关键字删除对象的属性,对原型也是适用的。删除了原型的属性后,该属性在原型链上就不可用了。在本例中,函数`bark`在执行了`delete Dog.prototype.bark`后不可用,然而后面的代码还在调用它。 当我们尝试调用一个不存在的函数时`TypeError`异常会被抛出。在本例中就是 `TypeError: pet.bark is not a function`,因为`pet.bark`是`undefined`. @@ -1688,7 +1690,7 @@ pet.bark(); --- -###### 56. 输出是什么? +###### 56. 输出是什么? ```javascript const set = new Set([1, 1, 2, 3, 4]); @@ -1704,7 +1706,7 @@ console.log(set);

答案

-#### 答案: D +#### 答案:D `Set`对象是独一无二的值的集合:也就是说同一个值在其中仅出现一次。 @@ -1715,7 +1717,7 @@ console.log(set); --- -###### 57. 输出是什么? +###### 57. 输出是什么? ```javascript // counter.js @@ -1740,18 +1742,18 @@ console.log(myCounter);

答案

-#### 答案: C +#### 答案:C -引入的模块是 _只读_ 的: 你不能修改引入的模块。只有导出他们的模块才能修改其值。 +引入的模块是 _只读_ 的:你不能修改引入的模块。只有导出他们的模块才能修改其值。 -当我们给`myCounter`增加一个值的时候会抛出一个异常: `myCounter`是只读的,不能被修改。 +当我们给`myCounter`增加一个值的时候会抛出一个异常:`myCounter`是只读的,不能被修改。

--- -###### 58. 输出是什么? +###### 58. 输出是什么? ```javascript const name = "Lydia"; @@ -1769,18 +1771,18 @@ console.log(delete age);
答案

-#### 答案: A +#### 答案:A -`delete`操作符返回一个布尔值: `true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 +`delete`操作符返回一个布尔值:`true`指删除成功,否则返回`false`. 但是通过 `var`, `const` 或 `let` 关键字声明的变量无法用 `delete` 操作符来删除。 -`name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`. +`name`变量由`const`关键字声明,所以删除不成功:返回 `false`. 而我们设定`age`等于`21`时,我们实际上添加了一个名为`age`的属性给全局对象。对象中的属性是可以删除的,全局对象也是如此,所以`delete age`返回`true`.

--- -###### 59. 输出是什么? +###### 59. 输出是什么? ```javascript const numbers = [1, 2, 3, 4, 5]; @@ -1797,7 +1799,7 @@ console.log(y);
答案

-#### 答案: C +#### 答案:C 我们可以通过解构赋值来解析来自对象的数组或属性的值,比如说: @@ -1807,7 +1809,7 @@ console.log(y); -`a`的值现在是`1`,`b`的值现在是`2`.而在题目中,我们是这么做的: +`a`的值现在是`1`,`b`的值现在是`2`.而在题目中,我们是这么做的: ```javascript [y] = [1, 2, 3, 4, 5]; @@ -1815,14 +1817,14 @@ console.log(y); -也就是说,`y`等于数组的第一个值就是数字`1`.我们输出`y`, 返回`1`. +也就是说,`y`等于数组的第一个值就是数字`1`.我们输出`y`,返回`1`.

--- -###### 60. 输出是什么? +###### 60. 输出是什么? ```javascript const user = { name: "Lydia", age: 21 }; @@ -1839,7 +1841,7 @@ console.log(admin);
答案

-#### 答案: B +#### 答案:B 扩展运算符`...`为对象的组合提供了可能。你可以复制对象中的键值对,然后把它们加到另一个对象里去。在本例中,我们复制了`user`对象键值对,然后把它们加入到`admin`对象中。`admin`对象就拥有了这些键值对,所以结果为`{ admin: true, name: "Lydia", age: 21 }`. @@ -1848,7 +1850,7 @@ console.log(admin); --- -###### 61. 输出是什么? +###### 61. 输出是什么? ```javascript const person = { name: "Lydia" }; @@ -1867,18 +1869,18 @@ console.log(Object.keys(person));

答案

-#### 答案: B +#### 答案:B -通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举(not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举(enumerable)_ 的属性,因此只剩下了`"name"`. +通过`defineProperty`方法,我们可以给对象添加一个新属性,或者修改已经存在的属性。而我们使用`defineProperty`方法给对象添加了一个属性之后,属性默认为 _不可枚举 (not enumerable)_. `Object.keys`方法仅返回对象中 _可枚举 (enumerable)_ 的属性,因此只剩下了`"name"`. -用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样的话, 相比于自己添加的属性,`defineProperty`方法添加的属性有了更多的控制权。 +用`defineProperty`方法添加的属性默认不可变。你可以通过`writable`, `configurable` 和 `enumerable`属性来改变这一行为。这样,`defineProperty`方法可以让您更好地控制要添加到对象的属性。

--- -###### 62. 输出是什么? +###### 62. 输出是什么? ```javascript const settings = { @@ -1899,21 +1901,21 @@ console.log(data);
答案

-#### 答案: A +#### 答案:A -`JSON.stringify`的第二个参数是 _替代者(replacer)_. 替代者(replacer)可以是个函数或数组,用以控制哪些值如何被转换为字符串。 +`JSON.stringify`的第二个参数是 _替代者 (replacer)_. 替代者 (replacer) 可以是个函数或数组,用以控制哪些值如何被转换为字符串。 -如果替代者(replacer)是个 _数组_ ,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来, `"username"`则被排除在外。 `data` 就等于 `"{"level":19, "health":90}"`. +如果替代者 (replacer) 是个 _数组_,那么就只有包含在数组中的属性将会被转化为字符串。在本例中,只有名为`"level"` 和 `"health"` 的属性被包括进来,`"username"`则被排除在外。`data` 就等于 `"{"level":19, "health":90}"`. -而如果替代者(replacer)是个 _函数_,这个函数将被对象的每个属性都调用一遍。 -函数返回的值会成为这个属性的值,最终体现在转化后的JSON字符串中(译者注:Chrome下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出JSON字符串),而如果返回值为`undefined`,则该属性会被排除在外。 +而如果替代者 (replacer) 是个 _函数_,这个函数将被对象的每个属性都调用一遍。 +函数返回的值会成为这个属性的值,最终体现在转化后的 JSON 字符串中(译者注:Chrome 下,经过实验,如果所有属性均返回同一个值的时候有异常,会直接将返回值作为结果输出而不会输出 JSON 字符串),而如果返回值为`undefined`,则该属性会被排除在外。

--- -###### 63. 输出是什么? +###### 63. 输出是什么? ```javascript let num = 10; @@ -1936,18 +1938,18 @@ console.log(num2);
答案

-#### 答案: A +#### 答案:A -一元操作符 `++` _先返回_ 操作值, _再累加_ 操作值。`num1`的值是`10`, 因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 +一元操作符 `++` _先返回_ 操作值,_再累加_ 操作值。`num1`的值是`10`,因为`increaseNumber`函数首先返回`num`的值,也就是`10`,随后再进行 `num`的累加。 -`num2`是`10`因为我们将 `num1`传入`increasePassedNumber`. `number`等于`10`(`num1`的值。同样道理,`++` _先返回_ 操作值, _再累加_ 操作值。) `number`是`10`,所以`num2`也是`10`. +`num2`是`10`因为我们将 `num1`传入`increasePassedNumber`. `number`等于`10`(`num1`的值。同样道理,`++` _先返回_ 操作值,_再累加_ 操作值。)`number`是`10`,所以`num2`也是`10`.

--- -###### 64. 输出什么? +###### 64. 输出什么? ```javascript const value = { number: 10 }; @@ -1970,22 +1972,22 @@ multiply(value);
答案

-#### 答案: C +#### 答案:C -在ES6中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"` ,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}` 。 +在 ES6 中,我们可以使用默认值初始化参数。如果没有给函数传参,或者传的参值为 `"undefined"`,那么参数的值将是默认值。上述例子中,我们将 `value` 对象进行了解构并传到一个新对象中,因此 `x` 的默认值为 `{number:10}`。 -默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}` ,因此打印出该数字的乘积值为`20`。 +默认参数在调用时才会进行计算,每次调用函数时,都会创建一个新的对象。我们前两次调用 `multiply` 函数且不传递值,那么每一次 `x` 的默认值都为 `{number:10}`,因此打印出该数字的乘积值为`20`。 -第三次调用 `multiply` 时,我们传递了一个参数,即对象`value`。 `*=`运算符实际上是`x.number = x.number * 2`的简写,我们修改了`x.number`的值,并打印出值`20`。 +第三次调用 `multiply` 时,我们传递了一个参数,即对象`value`。`*=`运算符实际上是`x.number = x.number * 2`的简写,我们修改了`x.number`的值,并打印出值`20`。 -第四次,我们再次传递`value`对象。 `x.number`之前被修改为`20`,所以`x.number * = 2`打印为`40`。 +第四次,我们再次传递`value`对象。`x.number`之前被修改为`20`,所以`x.number * = 2`打印为`40`。

--- -###### 65. 输出什么? +###### 65. 输出什么? ```javascript [1, 2, 3, 4].reduce((x, y) => console.log(x, y)); @@ -1999,9 +2001,9 @@ multiply(value);
答案

-#### 答案: D +#### 答案:D -`reducer` 函数接收4个参数: +`reducer` 函数接收 4 个参数: 1. Accumulator (acc) (累计器) 2. Current Value (cur) (当前值) @@ -2010,21 +2012,21 @@ multiply(value); `reducer` 函数的返回值将会分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。 -`reducer` 函数还有一个可选参数`initialValue`, 该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 +`reducer` 函数还有一个可选参数`initialValue`,该参数将作为第一次调用回调函数时的第一个参数的值。如果没有提供`initialValue`,则将使用数组中的第一个元素。 -在上述例子,`reduce`方法接收的第一个参数(Accumulator)是`x`, 第二个参数(Current Value)是`y`。 +在上述例子,`reduce`方法接收的第一个参数 (Accumulator) 是`x`,第二个参数 (Current Value) 是`y`。 在第一次调用时,累加器`x`为`1`,当前值`“y”`为`2`,打印出累加器和当前值:`1`和`2`。 -例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。 在下一次调用时,累加器为`undefined`,当前值为“3”, 因此`undefined`和`3`被打印出。 +例子中我们的回调函数没有返回任何值,只是打印累加器的值和当前值。如果函数没有返回值,则默认返回`undefined`。在下一次调用时,累加器为`undefined`,当前值为“3”,因此`undefined`和`3`被打印出。 -在第四次调用时,回调函数依然没有返回值。 累加器再次为 `undefined` ,当前值为“4”。 `undefined`和`4`被打印出。 +在第四次调用时,回调函数依然没有返回值。累加器再次为 `undefined`,当前值为“4”。`undefined`和`4`被打印出。

--- -###### 66. 使用哪个构造函数可以成功继承`Dog`类? +###### 66. 使用哪个构造函数可以成功继承`Dog`类? ```javascript class Dog { @@ -2065,19 +2067,19 @@ class Labrador extends Dog {
答案

-#### 答案: B +#### 答案:B -在子类中,在调用`super`之前不能访问到`this`关键字。 如果这样做,它将抛出一个`ReferenceError`:1和4将引发一个引用错误。 +在子类中,在调用`super`之前不能访问到`this`关键字。如果这样做,它将抛出一个`ReferenceError`:1 和 4 将引发一个引用错误。 -使用`super`关键字,需要用给定的参数来调用父类的构造函数。 父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 +使用`super`关键字,需要用给定的参数来调用父类的构造函数。父类的构造函数接收`name`参数,因此我们需要将`name`传递给`super`。 -`Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数2正确完成。 +`Labrador`类接收两个参数,`name`参数是由于它继承了`Dog`,`size`作为`Labrador`类的额外属性,它们都需要传递给`Labrador`的构造函数,因此使用构造函数 2 正确完成。

--- -###### 67. 输出什么? +###### 67. 输出什么? ```javascript // index.js @@ -2098,18 +2100,18 @@ export const sum = (a, b) => a + b;
答案

-#### 答案: B +#### 答案:B `import`命令是编译阶段执行的,在代码运行之前。因此这意味着被导入的模块会先运行,而导入模块的文件会后执行。 -这是CommonJS中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。 如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。 +这是 CommonJS 中`require()`和`import`之间的区别。使用`require()`,您可以在运行代码时根据需要加载依赖项。如果我们使用`require`而不是`import`,`running index.js`,`running sum.js`,`3`会被依次打印。

--- -###### 68. 输出什么? +###### 68. 输出什么? ```javascript console.log(Number(2) === Number(2)) @@ -2125,16 +2127,16 @@ console.log(Symbol('foo') === Symbol('foo'))
答案

-#### 答案: A +#### 答案:A -每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。 `Symbol`的值不依赖于传递的参数。 当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`, 这两个值是唯一的,彼此不相等,因此返回`false`。 +每个`Symbol`都是完全唯一的。传递给`Symbol`的参数只是给`Symbol`的一个描述。`Symbol`的值不依赖于传递的参数。当我们测试相等时,我们创建了两个全新的符号:第一个`Symbol('foo')`,第二个`Symbol('foo')`,这两个值是唯一的,彼此不相等,因此返回`false`。

--- -###### 69. 输出什么? +###### 69. 输出什么? ```javascript const name = "Lydia Hallie" @@ -2150,9 +2152,9 @@ console.log(name.padStart(2))
答案

-#### 答案: C +#### 答案:C -使用`padStart`方法,我们可以在字符串的开头添加填充。传递给此方法的参数是字符串的总长度(包含填充)。字符串`Lydia Hallie`的长度为`12`, 因此`name.padStart(13)`在字符串的开头只会插入1(`13 - 12 = 1`)个空格。 +使用`padStart`方法,我们可以在字符串的开头添加填充。传递给此方法的参数是字符串的总长度(包含填充)。字符串`Lydia Hallie`的长度为`12`,因此`name.padStart(13)`在字符串的开头只会插入 1(`13 - 12 = 1`)个空格。 如果传递给`padStart`方法的参数小于字符串的长度,则不会添加填充。 @@ -2161,7 +2163,7 @@ console.log(name.padStart(2)) --- -###### 70. 输出什么? +###### 70. 输出什么? ```javascript console.log("🥑" + "💻"); @@ -2175,9 +2177,9 @@ console.log("🥑" + "💻");

答案

-#### 答案: A +#### 答案:A -使用`+`运算符,您可以连接字符串。 上述情况,我们将字符串`“🥑”`与字符串`”💻“`连接起来,产生`”🥑💻“`。 +使用`+`运算符,您可以连接字符串。上述情况,我们将字符串`“🥑”`与字符串`”💻“`连接起来,产生`”🥑💻“`。

@@ -2208,9 +2210,9 @@ console.log(/* 2 */); // JavaScript loves you back ❤️
答案

-#### 答案: C +#### 答案:C -`generator`函数在遇到`yield`关键字时会“暂停”其执行。 首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`, 这意味着此时变量 `答案` 为`undefined` +`generator`函数在遇到`yield`关键字时会“暂停”其执行。首先,我们需要让函数产生字符串`Do you love JavaScript?`,这可以通过调用`game.next().value`来完成。上述函数的第一行就有一个`yield`关键字,那么运行立即停止了,`yield`表达式本身没有返回值,或者说总是返回`undefined`,这意味着此时变量 `答案` 为`undefined` `next`方法可以带一个参数,该参数会被当作上一个 `yield` 表达式的返回值。当我们调用`game.next("Yes").value`时,先前的 `yield` 的返回值将被替换为传递给`next()`函数的参数`"Yes"`。此时变量 `答案` 被赋值为 `"Yes"`,`if`语句返回`false`,所以`JavaScript loves you back ❤️`被打印。 @@ -2219,7 +2221,7 @@ console.log(/* 2 */); // JavaScript loves you back ❤️ --- -###### 72. 输出什么? +###### 72. 输出什么? ```javascript console.log(String.raw`Hello\nworld`); @@ -2233,7 +2235,7 @@ console.log(String.raw`Hello\nworld`);

答案

-#### 答案: C +#### 答案:C `String.raw`函数是用来获取一个模板字符串的原始字符串的,它返回一个字符串,其中忽略了转义符(`\n`,`\v`,`\t`等)。但反斜杠可能造成问题,因为你可能会遇到下面这种类似情况: @@ -2259,7 +2261,7 @@ String.raw`C:\Documents\Projects\table.html` --- -###### 73. 输出什么? +###### 73. 输出什么? ```javascript async function getData() { @@ -2278,9 +2280,9 @@ console.log(data);

答案

-#### 答案: C +#### 答案:C -异步函数始终返回一个promise。`await`仍然需要等待promise的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的promise,该promise并没有解决。 +异步函数始终返回一个 promise。`await`仍然需要等待 promise 的解决:当我们调用`getData()`并将其赋值给`data`,此时`data`为`getData`方法返回的一个挂起的 promise,该 promise 并没有解决。 如果我们想要访问已解决的值`"I made it!"`,可以在`data`上使用`.then()`方法: @@ -2293,7 +2295,7 @@ console.log(data); --- -###### 74. 输出什么? +###### 74. 输出什么? ```javascript function addToList(item, list) { @@ -2312,18 +2314,18 @@ console.log(result);

答案

-#### 答案: B +#### 答案:B -`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为1。 在数组中添加字符串`"apple"`后,长度变为2,并将从`addToList`函数返回。 +`push()`方法返回新数组的长度。一开始,数组包含一个元素(字符串`"banana"`),长度为 1。在数组中添加字符串`"apple"`后,长度变为 2,并将从`addToList`函数返回。 -`push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在push `item`之后返回`list`。 +`push`方法修改原始数组,如果你想从函数返回数组而不是数组长度,那么应该在 push `item`之后返回`list`。

--- -###### 75. 输出什么? +###### 75. 输出什么? ```javascript const box = { x: 10, y: 20 }; @@ -2343,22 +2345,22 @@ console.log(shape)
答案

-#### 答案: B +#### 答案:B `Object.freeze`使得无法添加、删除或修改对象的属性(除非属性的值是另一个对象)。 当我们创建变量`shape`并将其设置为等于冻结对象`box`时,`shape`指向的也是冻结对象。你可以使用`Object.isFrozen`检查一个对象是否被冻结,上述情况,`Object.isFrozen(shape)`将返回`true`。 -由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。 `x`仍然等于`10`,`{x:10,y:20}`被打印。 +由于`shape`被冻结,并且`x`的值不是对象,所以我们不能修改属性`x`。`x`仍然等于`10`,`{x:10,y:20}`被打印。 -注意,上述例子我们对属性`x`进行修改,可能会导致抛出TypeError异常(最常见但不仅限于严格模式下时)。 +注意,上述例子我们对属性`x`进行修改,可能会导致抛出 TypeError 异常(最常见但不仅限于严格模式下时)。

--- -###### 76. 输出什么? +###### 76. 输出什么? ```javascript const { name: myName } = { name: "Lydia" }; @@ -2374,11 +2376,11 @@ console.log(name);
答案

-#### 答案: D +#### 答案:D 当我们从右侧的对象解构属性`name`时,我们将其值`Lydia`分配给名为`myName`的变量。 -使用`{name:myName}`,我们是在告诉JavaScript我们要创建一个名为`myName`的新变量,并且其值是右侧对象的`name`属性的值。 +使用`{name:myName}`,我们是在告诉 JavaScript 我们要创建一个名为`myName`的新变量,并且其值是右侧对象的`name`属性的值。 当我们尝试打印`name`,一个未定义的变量时,就会引发`ReferenceError`。 @@ -2387,7 +2389,7 @@ console.log(name); --- -###### 77. 以下是个纯函数么? +###### 77. 以下是个纯函数么? ```javascript function sum(a, b) { @@ -2401,18 +2403,20 @@ function sum(a, b) {

答案

-#### 答案: A +#### 答案:A -纯函数一种若输入参数相同,则永远会得到相同输出的函数。 +纯函数在相同的输入值时,需产生相同的输出,其输出的结果,与输入值以外的其他隐藏信息或状态无关,也和由 I/O 设备产生的外部输出无关。 +纯函数不会产生副作用。 -`sum`函数总是返回相同的结果。 如果我们传递`1`和`2`,它将总是返回`3`而没有副作用。 如果我们传递`5`和`10`,它将总是返回`15`,依此类推,这是纯函数的定义。 +纯函数与副作用的定义可参考: +https://zh.wikipedia.org/wiki/%E5%89%AF%E4%BD%9C%E7%94%A8_(%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A7%91%E5%AD%A6)

--- -###### 78. 输出什么? +###### 78. 输出什么? ```javascript const add = () => { @@ -2442,26 +2446,26 @@ console.log(addFunction(5 * 2));
答案

-#### 答案: C +#### 答案:C -`add`函数是一个记忆函数。 通过记忆化,我们可以缓存函数的结果,以加快其执行速度。上述情况,我们创建一个`cache`对象,用于存储先前返回过的值。 +`add`函数是一个记忆函数。通过记忆化,我们可以缓存函数的结果,以加快其执行速度。上述情况,我们创建一个`cache`对象,用于存储先前返回过的值。 如果我们使用相同的参数多次调用`addFunction`函数,它首先检查缓存中是否已有该值,如果有,则返回缓存值,这将节省执行时间。如果没有,那么它将计算该值,并存储在缓存中。 我们用相同的值三次调用了`addFunction`函数: -在第一次调用,`num`等于`10`时函数的值尚未缓存,if语句`num in cache`返回`false`,else块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 +在第一次调用,`num`等于`10`时函数的值尚未缓存,if 语句`num in cache`返回`false`,else 块的代码被执行:`Calculated! 20`,并且其结果被添加到缓存对象,`cache`现在看起来像`{10:20}`。 -第二次,`cache`对象包含`10`的返回值。 if语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第二次,`cache`对象包含`10`的返回值。if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。 -第三次,我们将`5 * 2`(值为10)传递给函数。 `cache`对象包含`10`的返回值。 if语句 `num in cache` 返回`true`,`From cache! 20`被打印。 +第三次,我们将`5 * 2`(值为 10) 传递给函数。`cache`对象包含`10`的返回值。if 语句 `num in cache` 返回`true`,`From cache! 20`被打印。

--- -###### 79. 输出什么? +###### 79. 输出什么? ```javascript const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] @@ -2483,22 +2487,22 @@ for (let item of myLifeSummedUp) {
答案

-#### 答案: A +#### 答案:A -通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非Symbol的**属性。 在数组中,可枚举属性是数组元素的“键”, 即它们的索引。 类似于下面这个对象: +通过`for-in`循环,我们可以遍历一个对象**自有的**、**继承的**、**可枚举的**、**非 Symbol 的**属性。在数组中,可枚举属性是数组元素的“键”,即它们的索引。类似于下面这个对象: `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` 其中键则是可枚举属性,因此 `0`,`1`,`2`,`3`被记录。 -通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`, 因此`“☕”`,`“💻”`,`“🍷”`,`“🍫”`被打印。 +通过`for-of`循环,我们可以迭代**可迭代对象**(包括 `Array`,`Map`,`Set`,`String`,`arguments`等)。当我们迭代数组时,在每次迭代中,不同属性的值将被分配给变量`item`,因此`“☕”`,`“💻”`,`“🍷”`,`“🍫”`被打印。

--- -###### 80. 输出什么? +###### 80. 输出什么? ```javascript const list = [1 + 2, 1 * 2, 1 / 2] @@ -2513,18 +2517,18 @@ console.log(list)
答案

-#### 答案: C +#### 答案:C -数组元素可以包含任何值。 数字,字符串,布尔值,对象,数组,`null`,`undeifned`, 以及其他表达式,如日期,函数和计算。 +数组元素可以包含任何值。数字,字符串,布尔值,对象,数组,`null`,`undefined`,以及其他表达式,如日期,函数和计算。 -元素将等于返回的值。 `1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。 +元素将等于返回的值。`1 + 2`返回`3`,`1 * 2`返回'2`,'1 / 2`返回`0.5`。

--- -###### 81. 输出什么? +###### 81. 输出什么? ```javascript function sayHi(name) { @@ -2542,13 +2546,13 @@ console.log(sayHi())
答案

-#### 答案: B +#### 答案:B -默认情况下,如果不给函数传参,参数的值将为`undefined`。 上述情况,我们没有给参数`name`传值。 `name`等于`undefined`,并被打印。 +默认情况下,如果不给函数传参,参数的值将为`undefined`。上述情况,我们没有给参数`name`传值。`name`等于`undefined`,并被打印。 -在ES6中,我们可以使用默认参数覆盖此默认的`undefined`值。 例如: +在 ES6 中,我们可以使用默认参数覆盖此默认的`undefined`值。例如: -`function sayHi(name =“Lydia”){...}` +`function sayHi (name =“Lydia”){...}` 在这种情况下,如果我们没有传递值或者如果我们传递`undefined`,`name`总是等于字符串`Lydia` @@ -2557,7 +2561,7 @@ console.log(sayHi()) --- -###### 82. 输出什么? +###### 82. 输出什么? ```javascript var status = "😎" @@ -2585,17 +2589,17 @@ setTimeout(() => {

答案

-#### 答案: B +#### 答案:B -`this`关键字的指向取决于使用它的位置。 在**函数**中,比如`getStatus`,`this`指向的是调用它的对象,上述例子中`data`对象调用了`getStatus`,因此`this`指向的就是`data`对象。 当我们打印`this.status`时,`data`对象的`status`属性被打印,即`"🥑"`。 +`this`关键字的指向取决于使用它的位置。在**函数**中,比如`getStatus`,`this`指向的是调用它的对象,上述例子中`data`对象调用了`getStatus`,因此`this`指向的就是`data`对象。当我们打印`this.status`时,`data`对象的`status`属性被打印,即`"🥑"`。 -使用`call`方法,可以更改`this`指向的对象。`data.getStatus.call(this)`是将`this`的指向由`data`对象更改为全局对象。在全局对象上,有一个名为`status`的变量,其值为`”😎“`。 因此打印`this.status`时,会打印`“😎”`。 +使用`call`方法,可以更改`this`指向的对象。`data.getStatus.call(this)`是将`this`的指向由`data`对象更改为全局对象。在全局对象上,有一个名为`status`的变量,其值为`”😎“`。因此打印`this.status`时,会打印`“😎”`。

--- -###### 83. 输出什么? +###### 83. 输出什么? ```javascript const person = { @@ -2617,13 +2621,13 @@ console.log(person)
答案

-#### 答案: A +#### 答案:A -我们将变量`city`设置为等于`person`对象上名为`city`的属性的值。 这个对象上没有名为`city`的属性,因此变量`city`的值为`undefined`。 +我们将变量`city`设置为等于`person`对象上名为`city`的属性的值。这个对象上没有名为`city`的属性,因此变量`city`的值为`undefined`。 请注意,我们没有引用`person`对象本身,只是将变量`city`设置为等于`person`对象上`city`属性的当前值。 -然后,我们将`city`设置为等于字符串`“Amsterdam”`。 这不会更改person对象:没有对该对象的引用。 +然后,我们将`city`设置为等于字符串`“Amsterdam”`。这不会更改 person 对象:没有对该对象的引用。 因此打印`person`对象时,会返回未修改的对象。 @@ -2632,7 +2636,7 @@ console.log(person) --- -###### 84. 输出什么? +###### 84. 输出什么? ```javascript function checkAge(age) { @@ -2656,16 +2660,16 @@ console.log(checkAge(21))

答案

-#### 答案: C +#### 答案:C -`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西, 即上述情况`if / else`语句的花括号。 由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。 +`const`和`let`声明的变量是具有**块级作用域**的,块是大括号(`{}`)之间的任何东西,即上述情况`if / else`语句的花括号。由于块级作用域,我们无法在声明的块之外引用变量,因此抛出`ReferenceError`。

--- -###### 85. 什么样的信息将被打印? +###### 85. 什么样的信息将被打印? ```javascript fetch('https://www.website.com/api/user/1') @@ -2681,16 +2685,16 @@ fetch('https://www.website.com/api/user/1')
答案

-#### 答案: C +#### 答案:C -第二个`.then`中`res`的值等于前一个`.then`中的回调函数返回的值。 你可以像这样继续链接`.then`,将值传递给下一个处理程序。 +第二个`.then`中`res`的值等于前一个`.then`中的回调函数返回的值。你可以像这样继续链接`.then`,将值传递给下一个处理程序。

--- -###### 86. 哪个选项是将`hasName`设置为`true`的方法,前提是不能将`true`作为参数传递? +###### 86. 哪个选项是将`hasName`设置为`true`的方法,前提是不能将`true`作为参数传递? ```javascript function getName(name) { @@ -2706,9 +2710,9 @@ function getName(name) {
答案

-#### 答案: A +#### 答案:A -使用逻辑非运算符`!`,将返回一个布尔值,使用`!! name`,我们可以确定`name`的值是真的还是假的。 如果`name`是真实的,那么`!name`返回`false`。 `!false`返回`true`。 +使用逻辑非运算符`!`,将返回一个布尔值,使用`!! name`,我们可以确定`name`的值是真的还是假的。如果`name`是真实的,那么`!name`返回`false`。`!false`返回`true`。 通过将`hasName`设置为`name`,可以将`hasName`设置为等于传递给`getName`函数的值,而不是布尔值`true`。 @@ -2719,7 +2723,7 @@ function getName(name) {

-###### 87. 输出什么? +###### 87. 输出什么? ```javascript console.log("I want pizza"[0]) @@ -2733,18 +2737,18 @@ console.log("I want pizza"[0])
答案

-#### 答案: B +#### 答案:B -可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引0,依此类推。 在这种情况下,我们想要得到索引为0的元素,字符`'I'`被记录。 +可以使用方括号表示法获取字符串中特定索引的字符,字符串中的第一个字符具有索引 0,依此类推。在这种情况下,我们想要得到索引为 0 的元素,字符`'I'`被记录。 -请注意,IE7及更低版本不支持此方法。 在这种情况下,应该使用`.charAt()` +请注意,IE7 及更低版本不支持此方法。在这种情况下,应该使用`.charAt()`

--- -###### 88. 输出什么? +###### 88. 输出什么? ```javascript function sum(num1, num2 = num1) { @@ -2762,9 +2766,9 @@ sum(10)
答案

-#### 答案: B +#### 答案:B -您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。 我们将值`10`传递给`sum`函数。 如果`sum`函数只接收1个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。 `num2`的默认值是`num1`的值,即`10`。 ```num1 + num2```返回`20`。 +您可以将默认参数的值设置为函数的另一个参数,只要另一个参数定义在其之前即可。我们将值`10`传递给`sum`函数。如果`sum`函数只接收 1 个参数,则意味着没有传递`num2`的值,这种情况下,`num1`的值等于传递的值`10`。`num2`的默认值是`num1`的值,即`10`。```num1 + num2```返回`20`。 如果您尝试将默认参数的值设置为后面定义的参数,则可能导致参数的值尚未初始化,从而引发错误。比如: ```js @@ -2781,7 +2785,7 @@ test(3, 4) // 3 4 --- -###### 89. 输出什么? +###### 89. 输出什么? ```javascript // module.js @@ -2802,18 +2806,18 @@ console.log(data)

答案

-#### 答案: A +#### 答案:A -使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。 在`module.js`文件中,有两个导出:默认导出和命名导出。 默认导出是一个返回字符串“Hello World”的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 +使用`import * as name`语法,我们将`module.js`文件中所有`export`导入到`index.js`文件中,并且创建了一个名为`data`的新对象。在`module.js`文件中,有两个导出:默认导出和命名导出。默认导出是一个返回字符串“Hello World”的函数,命名导出是一个名为`name`的变量,其值为字符串`“Lydia”`。 -`data`对象具有默认导出的`default`属性,其他属性具有指定exports的名称及其对应的值。 +`data`对象具有默认导出的`default`属性,其他属性具有指定 exports 的名称及其对应的值。

--- -###### 90. 输出什么? +###### 90. 输出什么? ```javascript class Person { @@ -2834,7 +2838,7 @@ console.log(typeof member)
答案

-#### 答案: C +#### 答案:C 类是构造函数的语法糖,如果用构造函数的方式来重写`Person`类则将是: @@ -2851,7 +2855,7 @@ function Person() { --- -###### 91. 输出什么? +###### 91. 输出什么? ```javascript let newList = [1, 2, 3].push(4) @@ -2867,18 +2871,18 @@ console.log(newList.push(5))

答案

-#### 答案: D +#### 答案:D -`.push`方法返回数组的长度,而不是数组本身! 通过将`newList`设置为`[1,2,3].push(4)`,实际上`newList`等于数组的新长度:`4`。 +`.push`方法返回数组的长度,而不是数组本身!通过将`newList`设置为`[1,2,3].push(4)`,实际上`newList`等于数组的新长度:`4`。 -然后,尝试在`newList`上使用`.push`方法。 由于`newList`是数值`4`,抛出TypeError。 +然后,尝试在`newList`上使用`.push`方法。由于`newList`是数值`4`,抛出 TypeError。

--- -###### 92. 输出什么? +###### 92. 输出什么? ```javascript function giveLydiaPizza() { @@ -2899,16 +2903,16 @@ console.log(giveLydiaChocolate.prototype)
答案

-#### 答案: D +#### 答案:D -常规函数,例如`giveLydiaPizza`函数,有一个`prototype`属性,它是一个带有`constructor`属性的对象(原型对象)。 然而,箭头函数,例如`giveLydiaChocolate`函数,没有这个`prototype`属性。 尝试使用`giveLydiaChocolate.prototype`访问`prototype`属性时会返回`undefined`。 +常规函数,例如`giveLydiaPizza`函数,有一个`prototype`属性,它是一个带有`constructor`属性的对象(原型对象)。然而,箭头函数,例如`giveLydiaChocolate`函数,没有这个`prototype`属性。尝试使用`giveLydiaChocolate.prototype`访问`prototype`属性时会返回`undefined`。

--- -###### 93. 输出什么? +###### 93. 输出什么? ```javascript const person = { @@ -2929,12 +2933,12 @@ for (const [x, y] of Object.entries(person)) {
答案

-#### 答案: A +#### 答案:A `Object.entries()`方法返回一个给定对象自身可枚举属性的键值对数组,上述情况返回一个二维数组,数组每个元素是一个包含键和值的数组: -`[['name','Lydia'],['age',21]]` +`[['name','Lydia'],['age', 21]]` -使用`for-of`循环,我们可以迭代数组中的每个元素,上述情况是子数组。 我们可以使用`const [x,y]`在`for-of`循环中解构子数组。 `x`等于子数组中的第一个元素,`y`等于子数组中的第二个元素。 +使用`for-of`循环,我们可以迭代数组中的每个元素,上述情况是子数组。我们可以使用`const [x,y]`在`for-of`循环中解构子数组。`x`等于子数组中的第一个元素,`y`等于子数组中的第二个元素。 第一个子阵列是`[“name”,“Lydia”]`,其中`x`等于`name`,而`y`等于`Lydia`。 第二个子阵列是`[“age”,21]`,其中`x`等于`age`,而`y`等于`21`。 @@ -2944,7 +2948,7 @@ for (const [x, y] of Object.entries(person)) { --- -###### 94. 输出什么? +###### 94. 输出什么? ```javascript function getItems(fruitList, ...args, favoriteFruit) { @@ -2962,7 +2966,7 @@ getItems(["banana", "apple"], "pear", "orange")

答案

-#### 答案: D +#### 答案:D `... args`是剩余参数,剩余参数的值是一个包含所有剩余参数的数组,**并且只能作为最后一个参数**。上述示例中,剩余参数是第二个参数,这是不可能的,并会抛出语法错误。 @@ -2980,7 +2984,7 @@ getItems(["banana", "apple"], "pear", "orange") --- -###### 95. 输出什么? +###### 95. 输出什么? ```javascript function nums(a, b) { @@ -3005,26 +3009,26 @@ console.log(nums(1, 2))

答案

-#### 答案: B +#### 答案:B -在JavaScript中,我们不必显式地编写分号(`;`),但是JavaScript引擎仍然在语句之后自动添加分号。这称为**自动分号插入**。例如,一个语句可以是变量,或者像`throw`、`return`、`break`这样的关键字。 +在 JavaScript 中,我们不必显式地编写分号 (`;`),但是 JavaScript 引擎仍然在语句之后自动添加分号。这称为**自动分号插入**。例如,一个语句可以是变量,或者像`throw`、`return`、`break`这样的关键字。 -在这里,我们在新的一行上写了一个`return`语句和另一个值`a + b `。然而,由于它是一个新行,引擎并不知道它实际上是我们想要返回的值。相反,它会在`return`后面自动添加分号。你可以这样看: +在这里,我们在新的一行上写了一个`return`语句和另一个值`a + b `。然而,由于它是一个新行,引擎并不知道它实际上是我们想要返回的值。相反,它会在`return`后面自动添加分号。你可以这样看: ```javascript return; a + b ``` -这意味着永远不会到达`a + b`,因为函数在`return`关键字之后停止运行。如果没有返回值,就像这里,函数返回`undefined`。注意,在`if/else`语句之后没有自动插入! +这意味着永远不会到达`a + b`,因为函数在`return`关键字之后停止运行。如果没有返回值,就像这里,函数返回`undefined`。注意,在`if/else`语句之后没有自动插入!

--- -###### 96. 输出什么? +###### 96. 输出什么? ```javascript class Person { @@ -3051,10 +3055,10 @@ console.log(member.name)
答案

-#### 答案: B +#### 答案:B -我们可以将类设置为等于其他类/函数构造函数。 在这种情况下,我们将`Person`设置为`AnotherPerson`。 这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的name属性是`Sarah`。 +我们可以将类设置为等于其他类/函数构造函数。在这种情况下,我们将`Person`设置为`AnotherPerson`。这个构造函数的名字是`Sarah`,所以新的`Person`实例`member`上的 name 属性是`Sarah`。

@@ -3062,7 +3066,7 @@ console.log(member.name) --- -###### 97. 输出什么? +###### 97. 输出什么? ```javascript const info = { @@ -3081,19 +3085,19 @@ console.log(Object.keys(info))
答案

-#### 答案: D +#### 答案:D -`Symbol`类型是不可枚举的。`Object.keys`方法返回对象上的所有可枚举的键属性。`Symbol`类型是不可见的,并返回一个空数组。 记录整个对象时,所有属性都是可见的,甚至是不可枚举的属性。 +`Symbol`类型是不可枚举的。`Object.keys`方法返回对象上的所有可枚举的键属性。`Symbol`类型是不可见的,并返回一个空数组。记录整个对象时,所有属性都是可见的,甚至是不可枚举的属性。 -这是`Symbol`的众多特性之一:除了表示完全唯一的值(防止对象意外名称冲突,例如当使用2个想要向同一对象添加属性的库时),您还可以`隐藏`这种方式对象的属性(尽管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`方法访问 `Symbol`。 +这是`Symbol`的众多特性之一:除了表示完全唯一的值(防止对象意外名称冲突,例如当使用 2 个想要向同一对象添加属性的库时),您还可以`隐藏`这种方式对象的属性(尽管不完全。你仍然可以使用`Object.getOwnPropertySymbols()`方法访问 `Symbol`。

--- -###### 98. 输出什么? +###### 98. 输出什么? ```javascript const getList = ([x, ...y]) => [x, y] @@ -3106,7 +3110,7 @@ console.log(getList(list)) console.log(getUser(user)) ``` -- A: `[1, [2, 3, 4]]` and `undefined` +- A: `[1, [2, 3, 4]]` and `SyntaxError` - B: `[1, [2, 3, 4]]` and `{ name: "Lydia", age: 21 }` - C: `[1, 2, 3, 4]` and `{ name: "Lydia", age: 21 }` - D: `Error` and `{ name: "Lydia", age: 21 }` @@ -3114,27 +3118,27 @@ console.log(getUser(user))
答案

-#### 答案: A +#### 答案:A -`getList`函数接收一个数组作为其参数。 在`getList`函数的括号之间,我们立即解构这个数组。 您可以将其视为: +`getList`函数接收一个数组作为其参数。在`getList`函数的括号之间,我们立即解构这个数组。您可以将其视为: `[x, ...y] = [1, 2, 3, 4]` -使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。 在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。 在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 +使用剩余的参数`... y`,我们将所有剩余参数放在一个数组中。在这种情况下,其余的参数是`2`,`3`和`4`。 `y`的值是一个数组,包含所有其余参数。在这种情况下,`x`的值等于`1`,所以当我们打印`[x,y]`时,会打印`[1,[2,3,4]]`。 - `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须在圆括号之间编写它,否则不会返回任何值!下面的函数将返回一个对象: + `getUser`函数接收一个对象。对于箭头函数,如果只返回一个值,我们不必编写花括号。但是,如果您想从一个箭头函数返回一个对象,您必须将它写在圆括号之间,否则两个花括号之间的所有内容都将被解释为一个块语句!在这种情况下,花括号之间的代码不是有效的 JavaScript 代码,因此会抛出 SyntaxError。 -```const getUser = user => ({ name: user.name, age: user.age })``` +以下函数将返回一个对象: -由于在这种情况下不返回任何值,因此该函数返回`undefined`。 +`const getUser = user => ({ name: user.name, age: user.age })`

--- -###### 99. 输出什么? +###### 99. 输出什么? ```javascript const name = "Lydia" @@ -3150,22 +3154,22 @@ console.log(name())
答案

-#### 答案: C +#### 答案:C 变量`name`保存字符串的值,该字符串不是函数,因此无法调用。 -当值不是预期类型时,会抛出`TypeErrors`。 JavaScript期望`name`是一个函数,因为我们试图调用它。 但它是一个字符串,因此抛出`TypeError`:`name is not a function` +当值不是预期类型时,会抛出`TypeErrors`。JavaScript 期望`name`是一个函数,因为我们试图调用它。但它是一个字符串,因此抛出`TypeError`:`name is not a function` -当你编写了一些非有效的JavaScript时,会抛出语法错误,例如当你把`return`这个词写成`retrun`时。 -当JavaScript无法找到您尝试访问的值的引用时,抛出`ReferenceErrors`。 +当你编写了一些非有效的 JavaScript 时,会抛出语法错误,例如当你把`return`这个词写成`retrun`时。 +当 JavaScript 无法找到您尝试访问的值的引用时,抛出`ReferenceErrors`。

--- -###### 100. 输出什么? +###### 100. 输出什么? ```javascript // 🎉✨ This is my 100th question! ✨🎉 @@ -3182,19 +3186,19 @@ You should${'' && `n't`} see a therapist after so much JavaScript lol`
答案

-#### 答案: B +#### 答案:B -`[]`是一个真值。 使用`&&`运算符,如果左侧值是真值,则返回右侧值。 在这种情况下,左侧值`[]`是一个真值,所以返回`Im`。 +`[]`是一个真值。使用`&&`运算符,如果左侧值是真值,则返回右侧值。在这种情况下,左侧值`[]`是一个真值,所以返回`Im`。 -`""`是一个假值。 如果左侧值是假的,则不返回任何内容。 `n't`不会被退回。 +`""`是一个假值。如果左侧值是假的,则不返回任何内容。`n't`不会被退回。

--- -###### 101.输出什么? +###### 101.输出什么? ```javascript const one = (false || {} || null) @@ -3212,22 +3216,22 @@ console.log(one, two, three)
答案

-#### 答案: C +#### 答案:C -使用`||`运算符,我们可以返回第一个真值。 如果所有值都是假值,则返回最后一个值。 +使用`||`运算符,我们可以返回第一个真值。如果所有值都是假值,则返回最后一个值。 -`(false || {} || null)`:空对象`{}`是一个真值。 这是第一个(也是唯一的)真值,它将被返回。`one`等于`{}`。 +`(false || {} || null)`:空对象`{}`是一个真值。这是第一个(也是唯一的)真值,它将被返回。`one`等于`{}`。 -`(null || false ||“”)`:所有值都是假值。 这意味着返回传递的值`""`。 `two`等于`""`。 +`(null || false ||“”)`:所有值都是假值。这意味着返回传递的值`""`。`two`等于`""`。 -`([] || 0 ||“”)`:空数组`[]`是一个真值。 这是第一个返回的真值。 `three`等于`[]`。 +`([] || 0 ||“”)`:空数组`[]`是一个真值。这是第一个返回的真值。`three`等于`[]`。

--- -###### 102. 依次输出什么? +###### 102. 依次输出什么? ```javascript const myPromise = () => Promise.resolve('I have resolved!') @@ -3254,14 +3258,14 @@ secondFunction()
答案

-#### 答案: D +#### 答案:D -有了promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被resolved/rejected,并且执行栈为空时才使用这个值。 +有了 promise,我们通常会说:当我想要调用某个方法,但是由于它可能需要一段时间,因此暂时将它放在一边。只有当某个值被 resolved/rejected,并且执行栈为空时才使用这个值。 -我们可以在`async`函数中通过`.then`和`await`关键字获得该值。 尽管我们可以通过`.then`和`await`获得promise的价值,但是它们的工作方式有所不同。 +我们可以在`async`函数中通过`.then`和`await`关键字获得该值。尽管我们可以通过`.then`和`await`获得 promise 的价值,但是它们的工作方式有所不同。 -在 `firstFunction`中,当运行到`myPromise`方法时我们将其放在一边,即promise进入微任务队列,其他后面的代码(`console.log('second')`)照常运行,因此`second`被打印出,`firstFunction`方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,`I have resolved`被打印出。 +在 `firstFunction`中,当运行到`myPromise`方法时我们将其放在一边,即 promise 进入微任务队列,其他后面的代码(`console.log('second')`)照常运行,因此`second`被打印出,`firstFunction`方法到此执行完毕,执行栈中宏任务队列被清空,此时开始执行微任务队列中的任务,`I have resolved`被打印出。 在`secondFunction`方法中,我们通过`await`关键字,暂停了后面代码的执行,直到异步函数的值被解析才开始后面代码的执行。这意味着,它会等着直到 `myPromise` 以值`I have resolved`被解决之后,下一行`second`才开始执行。 @@ -3271,7 +3275,7 @@ secondFunction() --- -###### 103. 输出什么? +###### 103. 输出什么? ```javascript const set = new Set() @@ -3293,22 +3297,22 @@ for (let item of set) {

答案

-#### 答案: C +#### 答案:C -“+”运算符不仅用于添加数值,还可以使用它来连接字符串。 每当JavaScript引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 +“+”运算符不仅用于添加数值,还可以使用它来连接字符串。每当 JavaScript 引擎发现一个或多个值不是数字时,就会将数字强制为字符串。 -第一个是数字1。 1 + 2返回数字3。 +第一个是数字 1。1 + 2 返回数字 3。 -但是,第二个是字符串“Lydia”。 “Lydia”是一个字符串,2是一个数字:2被强制转换为字符串。 “Lydia”和“2”被连接起来,产生字符串“Lydia2”。 +但是,第二个是字符串“Lydia”。 “Lydia”是一个字符串,2 是一个数字:2 被强制转换为字符串。 “Lydia”和“2”被连接起来,产生字符串“Lydia2”。 -`{name:“ Lydia”}`是一个对象。 数字和对象都不是字符串,因此将二者都字符串化。 每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。 与“2”串联的“ [Object object]”成为“[Object object]2”。 +`{name:“Lydia”}`是一个对象。数字和对象都不是字符串,因此将二者都字符串化。每当我们对常规对象进行字符串化时,它就会变成`[Object object]`。与“2”串联的“ [Object object]”成为“[Object object]2”。

--- -###### 104. 结果是什么? +###### 104. 结果是什么? ```javascript Promise.resolve(5) @@ -3316,23 +3320,23 @@ Promise.resolve(5) - A: `5` - B: `Promise {: 5}` -- C: `Promise {: 5}` +- C: `Promise {: 5}` - D: `Error`
答案

-#### 答案: C +#### 答案:C -我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。 该方法本身返回带有已解析值的`Promise`。 如果您传递常规函数,它将是具有常规值的已解决`promise`。 如果你通过了promise,它将是一个已经resolved的且带有传的值的promise。 +我们可以将我们想要的任何类型的值传递`Promise.resolve`,无论是否`promise`。该方法本身返回带有已解析值的`Promise` (``)。如果您传递常规函数,它将是具有常规值的已解决`promise`。如果你通过了 promise,它将是一个已经 resolved 的且带有传的值的 promise。 -上述情况,我们传了数字5,因此返回一个resolved状态的promise,resolve值为`5` +上述情况,我们传了数字 5,因此返回一个 resolved 状态的 promise,resolve 值为`5`

-###### 105. 输出什么? +###### 105. 输出什么? ```javascript function compareMembers(person1, person2 = person) { @@ -3356,22 +3360,22 @@ compareMembers(person)
答案

-#### 答案: B +#### 答案:B -对象通过引用传递。 当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。 +对象通过引用传递。当我们检查对象的严格相等性(===)时,我们正在比较它们的引用。 我们将“person2”的默认值设置为“person”对象,并将“person”对象作为“person1”的值传递。 这意味着两个值都引用内存中的同一位置,因此它们是相等的。 -运行“ else”语句中的代码块,并记录`They are the same!` 。 +运行“else”语句中的代码块,并记录`They are the same!`。

--- -###### 106. 输出什么? +###### 106. 输出什么? ```javascript @@ -3396,14 +3400,14 @@ console.log(colorConfig.colors[1])
答案

-#### 答案: D +#### 答案:D -在JavaScript中,我们有两种访问对象属性的方法:括号表示法或点表示法。 在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“ colors”]`)。 +在 JavaScript 中,我们有两种访问对象属性的方法:括号表示法或点表示法。在此示例中,我们使用点表示法(`colorConfig.colors`)代替括号表示法(`colorConfig [“colors”]`)。 -使用点表示法,JavaScript会尝试使用该确切名称在对象上查找属性。 在此示例中,JavaScript尝试在colorconfig对象上找到名为colors的属性。 没有名为“colors”的属性,因此返回“undefined”。 -然后,我们尝试使用`[1]`访问第一个元素的值。 我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 +使用点表示法,JavaScript 会尝试使用该确切名称在对象上查找属性。在此示例中,JavaScript 尝试在 colorConfig 对象上找到名为 colors 的属性。没有名为“colors”的属性,因此返回“undefined”。 +然后,我们尝试使用`[1]`访问第一个元素的值。我们无法对未定义的值执行此操作,因此会抛出`Cannot read property '1' of undefined`。 -JavaScript解释(或取消装箱)语句。 当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。 只有这样,它才会评估该语句。 如果我们使用了colorConfig [colors [1]],它将返回colorConfig对象上red属性的值。 +JavaScript 解释(或取消装箱)语句。当我们使用方括号表示法时,它会看到第一个左方括号`[`并一直进行下去,直到找到右方括号`]`。只有这样,它才会评估该语句。如果我们使用了 colorConfig [colors [1]],它将返回 colorConfig 对象上 red 属性的值。

@@ -3411,7 +3415,7 @@ JavaScript解释(或取消装箱)语句。 当我们使用方括号表示法 --- -###### 107. 输出什么? +###### 107. 输出什么? ```javascript console.log('❤️' === '❤️') @@ -3423,16 +3427,16 @@ console.log('❤️' === '❤️')
答案

-#### 答案: A +#### 答案:A -在内部,表情符号是unicode。 heat表情符号的unicode是`“ U + 2764 U + FE0F”`。 对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回true。 +在内部,表情符号是 unicode。heat 表情符号的 unicode 是`“U + 2764 U + FE0F”`。对于相同的表情符号,它们总是相同的,因此我们将两个相等的字符串相互比较,这将返回 true。

--- -###### 108. 哪些方法修改了原数组? +###### 108. 哪些方法修改了原数组? ```javascript @@ -3454,9 +3458,9 @@ emojis.splice(1, 2, '✨')
答案

-#### 答案: D +#### 答案:D -使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。 在这种情况下,我们从索引1中删除了2个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji表情。 +使用`splice`方法,我们通过删除,替换或添加元素来修改原始数组。在这种情况下,我们从索引 1 中删除了 2 个元素(我们删除了`'🥑'`和`'😍'`),同时添加了✨emoji 表情。 `map`,`filter`和`slice`返回一个新数组,`find`返回一个元素,而`reduce`返回一个减小的值。 @@ -3465,7 +3469,7 @@ emojis.splice(1, 2, '✨') --- -###### 109. 输出什么? +###### 109. 输出什么? ```javascript const food = ['🍕', '🍫', '🥑', '🍔'] @@ -3484,18 +3488,18 @@ console.log(food)

答案

-#### 答案: A +#### 答案:A -我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号“🍕”的字符串。字符串是原始数据类型。在JavaScript中,原始数据类型通过值起作用 +我们将`info`对象上的`favoriteFood`属性的值设置为披萨表情符号“🍕”的字符串。字符串是原始数据类型。在 JavaScript 中,原始数据类型通过值起作用 -在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'` )。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。 food数组没有改变,因为favoriteFood的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。 +在这种情况下,我们将`info`对象上的`favoriteFood`属性的值设置为等于`food`数组中的第一个元素的值,字符串为披萨表情符号(`'🍕'`)。字符串是原始数据类型,并且通过值进行交互,我们更改`info`对象上`favoriteFood`属性的值。food 数组没有改变,因为 favoriteFood 的值只是该数组中第一个元素的值的复制,并且与该元素上的元素没有相同的内存引用食物`[0]`。当我们记录食物时,它仍然是原始数组`['🍕','🍫','🥑','🍔']`。

--- -###### 110. 这个函数干了什么? +###### 110. 这个函数干了什么? ```javascript JSON.parse() @@ -3509,20 +3513,20 @@ JSON.parse()
答案

-#### 答案: A +#### 答案:A -使用`JSON.parse()`方法,我们可以将JSON字符串解析为JavaScript值。 +使用`JSON.parse()`方法,我们可以将 JSON 字符串解析为 JavaScript 值。 ```javascript -// 将数字字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将数字字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonNumber = JSON.stringify(4) // '4' JSON.parse(jsonNumber) // 4 -// 将数组值字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将数组值字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonArray = JSON.stringify([1, 2, 3]) // '[1, 2, 3]' JSON.parse(jsonArray) // [1, 2, 3] -// 将对象字符串化为有效的JSON,然后将JSON字符串解析为JavaScript值: +// 将对象字符串化为有效的 JSON,然后将 JSON 字符串解析为 JavaScript 值: const jsonArray = JSON.stringify({ name: "Lydia" }) // '{"name":"Lydia"}' JSON.parse(jsonArray) // { name: 'Lydia' } ``` @@ -3532,7 +3536,7 @@ JSON.parse(jsonArray) // { name: 'Lydia' } --- -###### 111. 输出什么? +###### 111. 输出什么? ```javascript let name = 'Lydia' @@ -3553,13 +3557,13 @@ getName()

答案

-#### 答案: D +#### 答案:D -每个函数都有其自己的执行上下文。 `getName`函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量`name`。 上述情况,`getName`函数包含其自己的`name`变量:我们用`let`关键字和`Sarah`的值声明变量`name`。 +每个函数都有其自己的执行上下文。`getName`函数首先在其自身的上下文(范围)内查找,以查看其是否包含我们尝试访问的变量`name`。上述情况,`getName`函数包含其自己的`name`变量:我们用`let`关键字和`Sarah`的值声明变量`name`。 -带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被***初始化***。 在我们声明(初始化)它们之前,无法访问它们。 这称为“暂时性死区”。 当我们尝试在声明变量之前访问变量时,JavaScript会抛出`ReferenceError: Cannot access 'name' before initialization`。 +带有`let`关键字(和`const`)的变量被提升,但是与`var`不同,它不会被*** 初始化***。在我们声明(初始化)它们之前,无法访问它们。这称为“暂时性死区”。当我们尝试在声明变量之前访问变量时,JavaScript 会抛出`ReferenceError: Cannot access 'name' before initialization`。 -如果我们不在`getName`函数中声明`name`变量,则javascript引擎会查看原型练。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。 在这种情况下,它将打印`Lydia`: +如果我们不在`getName`函数中声明`name`变量,则 javascript 引擎会查看原型链。会找到其外部作用域有一个名为`name`的变量,其值为`Lydia`。在这种情况下,它将打印`Lydia`: ```javascript let name = 'Lydia' @@ -3602,18 +3606,18 @@ console.log(two.next().value)

答案

-#### 答案: C +#### 答案:C -通过 `yield` 关键字, 我们在 `Generator` 函数里执行`yield`表达式. 通过 `yield*` 关键字, 我们可以在一个`Generator` 函数里面执行(`yield`表达式)另一个 `Generator` 函数, 或可遍历的对象 (如数组). +通过 `yield` 关键字,我们在 `Generator` 函数里执行`yield`表达式。通过 `yield*` 关键字,我们可以在一个`Generator` 函数里面执行(`yield`表达式)另一个 `Generator` 函数,或可遍历的对象 (如数组). -在函数 `generatorOne` 中, 我们通过 `yield` 关键字 yield 了一个完整的数组 `['a', 'b', 'c']`。函数`one`通过`next`方法返回的对象的`value` 属性的值 (`one.next().value`) 等价于数组 `['a', 'b', 'c']`. +在函数 `generatorOne` 中,我们通过 `yield` 关键字 yield 了一个完整的数组 `['a', 'b', 'c']`。函数`one`通过`next`方法返回的对象的`value` 属性的值 (`one.next().value`) 等价于数组 `['a', 'b', 'c']`. ```javascript console.log(one.next().value) // ['a', 'b', 'c'] console.log(one.next().value) // undefined ``` -在函数 `generatorTwo` 中, 我们使用 `yield*` 关键字。就相当于函数`two`第一个`yield`的值, 等价于在迭代器中第一个 `yield` 的值。数组`['a', 'b', 'c']`就是这个迭代器. 第一个 `yield` 的值就是 `a`, 所以我们第一次调用 `two.next().value`时, 就返回`a`。 +在函数 `generatorTwo` 中,我们使用 `yield*` 关键字。就相当于函数`two`第一个`yield`的值,等价于在迭代器中第一个 `yield` 的值。数组`['a', 'b', 'c']`就是这个迭代器。第一个 `yield` 的值就是 `a`,所以我们第一次调用 `two.next().value`时,就返回`a`。 ```javascript console.log(two.next().value) // 'a' @@ -3641,16 +3645,16 @@ console.log(`${(x => x)('I love')} to program`)

答案

-#### 答案: A +#### 答案:A -带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 `(x => x)('I love')` 返回的值. 我们向箭头函数 `x => x` 传递 `'I love'` 作为参数。`x` 等价于返回的 `'I love'`。这就是结果 `I love to program`。 +带有模板字面量的表达式首先被执行。相当于字符串会包含表达式,这个立即执行函数 `(x => x)('I love')` 返回的值。我们向箭头函数 `x => x` 传递 `'I love'` 作为参数。`x` 等价于返回的 `'I love'`。这就是结果 `I love to program`。

--- -###### 114. 将会发生什么? +###### 114. 将会发生什么? ```javascript let config = { @@ -3670,9 +3674,9 @@ config = null
答案

-#### 答案: C +#### 答案:C -一般情况下当我们将对象赋值为 `null`, 那些对象会被进行 _垃圾回收(garbage collected)_ 因为已经没有对这些对象的引用了。然而,`setInterval`的参数是一个箭头函数(所以上下文绑定到对象 `config` 了),回调函数仍然保留着对 `config`的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,`setInterval` 的回调每1000ms (1s)会被调用一次。 +一般情况下当我们将对象赋值为 `null`,那些对象会被进行 _垃圾回收(garbage collected)_ 因为已经没有对这些对象的引用了。然而,`setInterval`的参数是一个箭头函数(所以上下文绑定到对象 `config` 了),回调函数仍然保留着对 `config`的引用。只要存在引用,对象就不会被垃圾回收。因为没有被垃圾回收,`setInterval` 的回调每 1000ms (1s) 会被调用一次。

@@ -3703,9 +3707,9 @@ myMap.get(() => 'greeting')
答案

-#### 答案: B +#### 答案:B -当通过 `set` 方法添加一个键值对,一个传递给 `set`方法的参数将会是键名,第二个参数将会是值。在这个case里,键名为 _函数_ `() => 'greeting'`,值为`'Hello world'`。 `myMap` 现在就是 `{ () => 'greeting' => 'Hello world!' }`。 +当通过 `set` 方法添加一个键值对,一个传递给 `set`方法的参数将会是键名,第二个参数将会是值。在这个 case 里,键名为 _函数_ `() => 'greeting'`,值为`'Hello world'`。 `myMap` 现在就是 `{ () => 'greeting' => 'Hello world!' }`。 1 是错的,因为键名不是 `'greeting'` 而是 `() => 'greeting'`。 3 是错的,因为我们给`get` 方法传递了一个新的函数。对象受 _引用_ 影响。函数也是对象,因此两个函数严格上并不等价,尽管他们相同:他们有两个不同的内存引用地址。 @@ -3743,13 +3747,13 @@ console.log(person)

答案

-#### 答案: C +#### 答案:C 函数 `changeAge` 和函数 `changeAgeAndName` 有着不同的参数,定义一个 _新_ 生成的对象 `{ ...person }`。这个对象有着所有 `person` 对象 中 k/v 值的副本。 -首项, 我们调用 `changeAge` 函数并传递 `person` 对象作为它的参数。这个函数对 `age` 属性进行加一操作。`person` 现在是 `{ name: "Lydia", age: 22 }`。 +首项,我们调用 `changeAge` 函数并传递 `person` 对象作为它的参数。这个函数对 `age` 属性进行加一操作。`person` 现在是 `{ name: "Lydia", age: 22 }`。 -然后,我们调用函数 `changeAgeAndName` ,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象: `{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。 +然后,我们调用函数 `changeAgeAndName`,然而我们没有传递参数。取而代之,`x` 的值等价 _new_ 生成的对象:`{ ...person }`。因为它是一个新生成的对象,它并不会对对象 `person` 造成任何副作用。`person` 仍然等价于 `{ name: "Lydia", age: 22 }`。

@@ -3772,9 +3776,9 @@ function sumValues(x, y, z) {
答案

-#### 答案: C +#### 答案:C -通过展开操作符 `...`,我们可以 _暂开_ 单个可迭代的元素。函数 `sumValues` function 接收三个参数: `x`, `y` 和 `z`。`...[1, 2, 3]` 的执行结果为 `1, 2, 3`,将会传递给函数 `sumValues`。 +通过展开操作符 `...`,我们可以 _暂开_ 单个可迭代的元素。函数 `sumValues` function 接收三个参数:`x`, `y` 和 `z`。`...[1, 2, 3]` 的执行结果为 `1, 2, 3`,将会传递给函数 `sumValues`。

@@ -3798,9 +3802,9 @@ console.log(list[(num += 1)]);
答案

-#### 答案: B +#### 答案:B -通过 `+=` 操作符,我们对值 `num` 进行加 `1` 操作。 `num` 有初始值 `1`,因此 `1 + 1` 的执行结果为 `2`。数组 `list` 的第二项为 🥰,`console.log(list[2])` 输出 🥰. +通过 `+=` 操作符,我们对值 `num` 进行加 `1` 操作。`num` 有初始值 `1`,因此 `1 + 1` 的执行结果为 `2`。数组 `list` 的第二项为 🥰,`console.log(list[2])` 输出 🥰.

@@ -3829,21 +3833,21 @@ console.log(member.getLastName?.()); ``` - A: `undefined` `undefined` `undefined` `undefined` -- B: `Mara` `undefined` `Lydia Hallie` `undefined` +- B: `Mara` `undefined` `Lydia Hallie` `ReferenceError` - C: `Mara` `null` `Lydia Hallie` `null` - D: `null` `ReferenceError` `null` `ReferenceError`
答案

-#### 答案: B +#### 答案:B 通过 ES10 或 TS3.7+[可选链操作符 `?.`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE),我们不再需要显式检测更深层的嵌套值是否有效。如果我们尝试获取 `undefined` 或 `null` 的值 (_nullish_),表达将会短路并返回 `undefined`. -`person.pet?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 -`person.pet?.family?.name`: `person` 有一个名为 `pet` 的属性: `person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性, `person.pet.family` 是 nullish。表达式返回 `undefined`。 -`person.getFullName?.()`: `person` 有一个名为 `getFullName` 的属性: `person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 -`member.getLastName?.()`: `member` is not defined: `member.getLastName()` is nullish. The expression returns `undefined`. +`person.pet?.name`:`person` 有一个名为 `pet` 的属性:`person.pet` 不是 nullish。它有个名为 `name` 的属性,并返回字符串 `Mara`。 +`person.pet?.family?.name`:`person` 有一个名为 `pet` 的属性:`person.pet` 不是 nullish. `pet` _并没有_ 一个名为 `family` 的属性,`person.pet.family` 是 nullish。表达式返回 `undefined`。 +`person.getFullName?.()`:`person` 有一个名为 `getFullName` 的属性:`person.getFullName()` 不是 nullish 并可以被调用,返回字符串 `Lydia Hallie`。 +`member.getLastName?.()`: 变量`member` 不存在,因此会抛出错误`ReferenceError`。

@@ -3870,16 +3874,16 @@ if (groceries.indexOf("banana")) {
答案

-#### 答案: B +#### 答案:B -我们传递了一个状态 `groceries.indexOf("banana")` 给if条件语句。`groceries.indexOf("banana")` 返回 `0`, 一个 falsy 的值。因为if条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出. +我们传递了一个状态 `groceries.indexOf("banana")` 给 if 条件语句。`groceries.indexOf("banana")` 返回 `0`,一个 falsy 的值。因为 if 条件语句的状态为 falsy,`else` 块区内的代码执行,并且 `We don't have to buy bananas!` 被输出。

--- -###### 121. 输出什么? +###### 121. 输出什么? ```javascript const config = { @@ -3900,9 +3904,9 @@ console.log(config.language);
答案

-#### 答案: D +#### 答案:D -方法 `language` 是一个 `setter`。Setters 并不保存一个实际值,它们的使命在于 _修改_ 属性。当调用方法 `setter`, 返回 `undefined`。 +方法 `language` 是一个 `setter`。Setters 并不保存一个实际值,它们的使命在于 _修改_ 属性。当调用方法 `setter`,返回 `undefined`。

@@ -3926,9 +3930,9 @@ console.log(!typeof name === "string");
答案

-#### 答案: C +#### 答案:C -`typeof name` 返回 `"string"`。字符串 `"string"` 是一个 truthy 的值,因此 `!typeof name` 返回一个布尔值 `false`。 `false === "object"` 和 `false === "string"` 都返回 `false`。 +`typeof name` 返回 `"string"`。字符串 `"string"` 是一个 truthy 的值,因此 `!typeof name` 返回一个布尔值 `false`。`false === "object"` 和 `false === "string"` 都返回 `false`。 (如果我们想检测一个值的类型,我们应该用 `!==` 而不是 `!typeof`) @@ -3937,7 +3941,7 @@ console.log(!typeof name === "string"); --- -###### 123. 输出什么? +###### 123. 输出什么? ```javascript const add = x => y => z => { @@ -3956,7 +3960,7 @@ add(4)(5)(6);

答案

-#### 答案: A +#### 答案:A 函数 `add` 是一个返回 返回箭头函数的箭头函数 的箭头函数(still with me?)。第一个函数接收一个值为 `4` 的参数 `x`。我们调用第二个函数,它接收一个值为 `5` 的参数 `y`。然后我们调用第三个函数,它接收一个值为 `6` 的参数 `z`。当我们尝试在最后一个箭头函数中获取 `x`, `y` 和 `z` 的值,JS 引擎根据作用域链去找 `x` 和 `y` 的值。得到 `4` `5` `6`. @@ -3990,9 +3994,9 @@ async function* range(start, end) {

答案

-#### 答案: C +#### 答案:C -我们给 函数range 传递: `Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`: 第一个返回 `Promise{1}`, 第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promsie,promise数组的resolved _值_ 以此为: `1`,`2`,`3`. +我们给 函数 range 传递:`Promise{1}`, `Promise{2}`, `Promise{3}`,Generator 函数 `range` 返回一个全是 async object promise 数组。我们将 async object 赋值给变量 `gen`,之后我们使用`for await ... of` 进行循环遍历。我们将返回的 Promise 实例赋值给 `item`:第一个返回 `Promise{1}`,第二个返回 `Promise{2}`,之后是 `Promise{3}`。因为我们正 _awaiting_ `item` 的值,resolved 状态的 promise,promise 数组的 resolved _值_ 以此为:`1`,`2`,`3`.

@@ -4017,9 +4021,9 @@ myFunc(1, 2, 3);
答案

-#### 答案: D +#### 答案:D -`myFunc` 期望接收一个包含 `x`, `y` 和 `z` 属性的对象作为它的参数。因为我们仅仅传递三个单独的数字值 (1, 2, 3) 而不是一个含有 `x`, `y` 和 `z` 属性的对象 ({x: 1, y: 2, z: 3}), `x`, `y` 和 `z` 有着各自的默认值 `undefined`. +`myFunc` 期望接收一个包含 `x`, `y` 和 `z` 属性的对象作为它的参数。因为我们仅仅传递三个单独的数字值 (1, 2, 3) 而不是一个含有 `x`, `y` 和 `z` 属性的对象 ({x: 1, y: 2, z: 3}),`x`, `y` 和 `z` 有着各自的默认值 `undefined`.

@@ -4030,15 +4034,15 @@ myFunc(1, 2, 3); ```javascript function getFine(speed, amount) { - const formattedSpeed = new Intl.NumberFormat({ + const formattedSpeed = new Intl.NumberFormat( 'en-US', { style: 'unit', unit: 'mile-per-hour' } - }).format(speed) + ).format(speed) - const formattedAmount = new Intl.NumberFormat({ + const formattedAmount = new Intl.NumberFormat( 'en-US', { style: 'currency', currency: 'USD' } - }).format(amount) + ).format(amount) return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}` } @@ -4054,9 +4058,9 @@ console.log(getFine(130, 300))
答案

-#### 答案: B +#### 答案:B -通过方法 `Intl.NumberFormat`,我们可以格式化任意区域的数字值。我们对数字值 `130` 进行 `mile-per-hour` 作为 `unit` 的 `en-US` 区域 格式化,结果为 `130 mph`。对数字值 `300` 进行 `USD` 作为 `currentcy` 的 `en-US` 区域格式化,结果为 `$300.00`. +通过方法 `Intl.NumberFormat`,我们可以格式化任意区域的数字值。我们对数字值 `130` 进行 `mile-per-hour` 作为 `unit` 的 `en-US` 区域 格式化,结果为 `130 mph`。对数字值 `300` 进行 `USD` 作为 `currency` 的 `en-US` 区域格式化,结果为 `$300.00`.

@@ -4080,7 +4084,7 @@ console.log(spookyItems);
答案

-#### 答案: B +#### 答案:B 通过解构对象们,我们可以从右手边的对象中拆出值,并且将拆出的值分配给左手边对象同名的属性。在这种情况下,我们将值 "💀" 分配给 `spookyItems[3]`。相当于我们正在篡改数组 `spookyItems`,我们给它添加了值 "💀"。当输出 `spookyItems` 时,结果为 `["👻", "🎃", "🕸", "💀"]`。 @@ -4110,11 +4114,11 @@ console.log(isNaN(age));

答案

-#### 答案: C +#### 答案:C 通过方法 `Number.isNaN`,你可以检测你传递的值是否为 _数字值_ 并且是否等价于 `NaN`。`name` 不是一个数字值,因此 `Number.isNaN(name)` 返回 `false`。`age` 是一个数字值,但它不等价于 `NaN`,因此 `Number.isNaN(age)` 返回 `false`. -通过方法 `isNaN`, 你可以检测你传递的值是否一个 number。`name` 不是一个 `number`,因此 `isNaN(name)` 返回 `true`. `age` 是一个 `number` 因此 `isNaN(age)` 返回 `false`. +通过方法 `isNaN`,你可以检测你传递的值是否一个 number。`name` 不是一个 `number`,因此 `isNaN(name)` 返回 `true`. `age` 是一个 `number` 因此 `isNaN(age)` 返回 `false`.

@@ -4142,9 +4146,9 @@ getInfo();
答案

-#### 答案: D +#### 答案:D -通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死去_。在函数 `getInfo` 中, 变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行log之前,变量 `randomValue` 仍未被初始化: 错误`ReferenceError` 被抛出! JS引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。 +通过 `const` 关键字声明的变量在被初始化之前不可被引用:这被称之为 _暂时性死区_。在函数 `getInfo` 中,变量 `randomValue` 声明在`getInfo` 的作用域的此法环境中。在想要对 `typeof randomValue` 进行 log 之前,变量 `randomValue` 仍未被初始化:错误`ReferenceError` 被抛出!JS 引擎并不会根据作用域链网上寻找该变量,因为我们已经在 `getInfo` 函数中声明了 `randomValue` 变量。

@@ -4175,9 +4179,9 @@ const myPromise = Promise.resolve("Woah some cool data");
答案

-#### 答案: C +#### 答案:C -在 `try` 块区,我们打印 `myPromise` 变量的 awaited 值: `"Woah some cool data"`。因为`try` 块区没有错误抛出,`catch` 块区的代码并不执行。`finally` 块区的代码 _总是_ 执行,`"Oh finally!"` 被输出。 +在 `try` 块区,我们打印 `myPromise` 变量的 awaited 值:`"Woah some cool data"`。因为`try` 块区没有错误抛出,`catch` 块区的代码并不执行。`finally` 块区的代码 _总是_ 执行,`"Oh finally!"` 被输出。

@@ -4200,9 +4204,9 @@ console.log(emojis.flat(1));
答案

-#### 答案: B +#### 答案:B -通过方法 `flat`, 我们可以创建一个新的, 已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个case里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`. +通过方法 `flat`,我们可以创建一个新的,已被扁平化的数组。被扁平化的深度取决于我们传递的值。在这个 case 里,我们传递了值 `1` (并不必要,这是默认值),相当于只有第一层的数组才会被连接。即这个 case 里的 `['🥑']` and `['✨', '✨', ['🍕', '🍕']]`。连接这两个数组得到结果 `['🥑', '✨', '✨', ['🍕', '🍕']]`.

@@ -4240,15 +4244,15 @@ console.log(counterOne.count);
答案

-#### 答案: D +#### 答案:D -`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里, 和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在, `counterOne.count` 为 `2`. +`counterOne` 是类 `Counter` 的一个实例。类 Counter 包含一个`count` 属性在它的构造函数里,和一个 `increment` 方法。首先,我们通过 `counterOne.increment()` 调用方法 `increment` 两次。现在,`counterOne.count` 为 `2`. 然后,我们创建一个新的变量 `counterTwo` 并将 `counterOne` 的引用地址赋值给它。因为对象受引用地址的影响,我们刚刚创建了一个新的对象,其引用地址和 `counterOne` 的等价。因此它们指向同一块内存地址,任何对其的副作用都会影响 `counterTwo`。现在 `counterTwo.count` 为 `2`。 -我们调用 `counterTwo.increment()` 将 `count` 的值设为 `3`。然后,我们打印 `counterOne` 里的count,结果为 `3`。 +我们调用 `counterTwo.increment()` 将 `count` 的值设为 `3`。然后,我们打印 `counterOne` 里的 count,结果为 `3`。 @@ -4264,14 +4268,14 @@ const myPromise = Promise.resolve(Promise.resolve("Promise!")); function funcOne() { myPromise.then(res => res).then(res => console.log(res)); - setTimeout(() => console.log("Timeout!", 0)); + setTimeout(() => console.log("Timeout!"), 0); console.log("Last line!"); } async function funcTwo() { const res = await myPromise; console.log(await res); - setTimeout(() => console.log("Timeout!", 0)); + setTimeout(() => console.log("Timeout!"), 0); console.log("Last line!"); } @@ -4287,13 +4291,13 @@ funcTwo();

答案

-#### 答案: D +#### 答案:D -首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当JS引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于event loop的文章.) +首先,我们调用 `funcOne`。在函数 `funcOne` 的第一行,我们调用`myPromise` promise _异步操作_。当 JS 引擎在忙于执行 promise,它继续执行函数 `funcOne`。下一行 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 (详情请参考我关于 event loop 的文章.) -promise 和 timeout 都是异步操作,函数继续执行当JS引擎忙于执行promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出, 因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`, 调用栈不为空,`setTimeout` 的回调仍不能入栈。 +promise 和 timeout 都是异步操作,函数继续执行当 JS 引擎忙于执行 promise 和 处理 `setTimeout` 的回调。相当于 `Last line!` 首先被输出,因为它不是异步操作。执行完 `funcOne` 的最后一行,promise 状态转变为 resolved,`Promise!` 被打印。然而,因为我们调用了 `funcTwo()`,调用栈不为空,`setTimeout` 的回调仍不能入栈。 -我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字, 我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。 接着输出 `Promise!`。 +我们现在处于 `funcTwo`,先 _awaiting_ myPromise。通过 `await` 关键字,我们暂停了函数的执行直到 promise 状态变为 resolved (或 rejected)。然后,我们输出 `res` 的 awaited 值(因为 promise 本身返回一个 promise)。接着输出 `Promise!`。 下一行就是 _异步操作_ `setTimeout`,其回调函数被 Web API 调用。 @@ -4324,7 +4328,7 @@ import * as sum from "./sum";

答案

-#### 答案: C +#### 答案:C 使用符号 `*`,我们引入文件中的所有值,包括默认和具名。如果我们有以下文件: @@ -4384,13 +4388,13 @@ person.name;

答案

-#### 答案: C +#### 答案:C -使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我门 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 +使用 Proxy 对象,我们可以给一个对象添加自定义行为。在这个 case,我们传递一个包含以下属性的对象 `handler` : `set` and `get`。每当我们 _设置_ 属性值时 `set` 被调用,每当我们 _获取_ 时 `get` 被调用。 -第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性, `get` 将被调用。 +第一个参数是一个空对象 `{}`,作为 `person` 的值。对于这个对象,自定义行为被定义在对象 `handler`。如果我们向对象 `person` 添加属性,`set` 将被调用。如果我们获取 `person` 的属性,`get` 将被调用。 -首先,我们向 proxy 对象(`person.name = "Lydia"`)添加一个属性 `name`。`set` 被调用并输出 `"Added a new property!"`。 +首先,我们向 proxy 对象 (`person.name = "Lydia"`) 添加一个属性 `name`。`set` 被调用并输出 `"Added a new property!"`。 然后,我们获取 proxy 对象的一个属性,对象 handler 的属性 `get` 被调用。输出 `"Accessed a property!"`。 @@ -4415,7 +4419,7 @@ Object.seal(person);

答案

-#### 答案: A +#### 答案:A 使用 `Object.seal` 我们可以防止新属性 _被添加_,或者存在属性 _被移除_. @@ -4447,7 +4451,7 @@ Object.freeze(person);

答案

-#### 答案: C +#### 答案:C 使用方法 `Object.freeze` 对一个对象进行 _冻结_。不能对属性进行添加,修改,删除。 @@ -4479,11 +4483,11 @@ myFunc(3);

答案

-#### 答案: A +#### 答案:A -首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`, 而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为2的 `num` 作为参数。函数 `add` 返回 `4` 作为 `value` 的值。 +首先我们不传递任何参数调用 `myFunc()`。因为我们没有传递参数,`num` 和 `value` 获取它们各自的默认值:num 为 `2`,而 `value` 为函数 `add` 的返回值。对于函数 `add`,我们传递值为 2 的 `num` 作为参数。函数 `add` 返回 `4` 作为 `value` 的值。 -然后,我们调用 `myFunc(3)` 并传递值 `3` 参数 `num` 的值。我们没有给 `value` 传递值。因为我们没有给参数 `value` 传递值,它获取默认值:函数 `add` 的返回值。对于函数 `add`,我们传递值为3的 `num`给它。函数 `add` 返回 `6` 作为 `value` 的值。 +然后,我们调用 `myFunc(3)` 并传递值 `3` 参数 `num` 的值。我们没有给 `value` 传递值。因为我们没有给参数 `value` 传递值,它获取默认值:函数 `add` 的返回值。对于函数 `add`,我们传递值为 3 的 `num`给它。函数 `add` 返回 `6` 作为 `value` 的值。

@@ -4519,9 +4523,9 @@ console.log(counter.#number)
答案

-#### 答案: D +#### 答案:D -在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它! +在 ES2020 中,通过 `#` 我们可以给 class 添加私有变量。在 class 的外部我们无法获取该值。当我们尝试输出 `counter.#number`,语法错误被抛出:我们无法在 class `Counter` 外部获取它!

@@ -4561,11 +4565,11 @@ obj.next(); // { value: "Lisa", done: false }
答案

-#### 答案: B +#### 答案:B 为了遍历 `teams` 数组中对象的属性 `members` 中的每一项,我们需要将 `teams[i].members` 传递给 Generator 函数 `getMembers`。Generator 函数返回一个 generator 对象。为了遍历这个 generator 对象中的每一项,我们需要使用 `yield*`. -如果我们没有写 `yield`,`return yield` 或者 `return`,整个 Generator 函数不会第一时间 return 当我们调用 `next` 方法. +如果我们没有写 `yield`,`return yield` 或者 `return`,整个 Generator 函数不会第一时间 return 当我们调用 `next` 方法。

@@ -4600,7 +4604,7 @@ console.log(person.hobbies);
答案

-#### 答案: C +#### 答案:C 函数 `addHobby` 接受两个参数,`hobby` 和有着对象 `person` 中数组 `hobbies` 默认值的 `hobbies`。 @@ -4608,7 +4612,7 @@ console.log(person.hobbies); 然后,我们调用函数 `addHobby`,并给 `hobby` 传递 `"dancing"`。我们不向 `hobbies` 传递值,因此它获取其默认值 —— 对象 `person` 的 属性 `hobbies`。我们向数组 `person.hobbies` push `dancing`。 -最后,我们调用函数 `addHobby`,并向 `hobby` 传递 值 `"bdaking"`,并且向 `hobbies` 传递 `person.hobbies`。我们向数组 `person.hobbies` push `dancing`。 +最后,我们调用函数 `addHobby`,并向 `hobby` 传递 值 `"baking"`,并且向 `hobbies` 传递 `person.hobbies`。我们向数组 `person.hobbies` push `dancing`。 pushing `dancing` 和 `baking` 之后,`person.hobbies` 的值为 `["coding", "dancing", "baking"]` @@ -4644,9 +4648,9 @@ const pet = new Flamingo();

答案

-#### 答案: B +#### 答案:B -我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`, 之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。 +我们创建了类 `Flamingo` 的实例 `pet`。当我们实例化这个实例,`Flamingo` 中的 `constructor` 被调用。首相,输出 `"I'm pink. 🌸"`,之后我们调用`super()`。`super()` 调用父类的构造函数,`Bird`。`Bird` 的构造函数被调用,并输出 `"I'm a bird. 🦢"`。

@@ -4672,9 +4676,9 @@ const emojis = ["🎄", "🎅🏼", "🎁", "⭐"];
答案

-#### 答案: D +#### 答案:D -`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。而然,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值, 拼接,又或者将数组的长度设置为0。 +`const` 关键字意味着我们不能 _重定义_ 变量中的值,它 _仅可读_。然而,值本身不可修改。数组 `emojis` 中的值可被修改,如 push 新的值,拼接,又或者将数组的长度设置为 0。

@@ -4694,15 +4698,387 @@ const person = { - A: 不需要,对象默认就是可迭代的 - B: `*[Symbol.iterator]() { for (let x in this) yield* this[x] }` -- C: `*[Symbol.iterator]() { for (let x in this) yield* Object.values(this) }` +- C: `*[Symbol.iterator]() { yield* Object.values(this) }` - D: `*[Symbol.iterator]() { for (let x in this) yield this }`
答案

-#### 答案: C +#### 答案:C + +对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器 symbol `[Symbol.iterator]` 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 `*[Symbol.iterator]() {}`。如果我们想要返回数组 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,这个 generator 函数一定要 yield 对象 `person` 的`Object.values`。 + +

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

+ +#### 答案:C + +在 `forEach` 循环内部的 `if` 会判断 `num` 的值是 truthy 或者是 falsy。因为 `nums` 数组的第一个数字是 `0`,一个 falsy 值,`if` 语句代码块不会被执行。`count` 仅仅在 `nums` 数组的其他 3 个数字 `1`,`2`,`3` 时加 1。因为 `count` 执行了 3 次加 `1` 运算,所以 `count` 的值为 `3`。 + +

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

+ +#### 答案:D + +`?` 允许我们去选择性地访问对象内部更深层的嵌套属性。我们尝试打印 `fruits` 数组索引值为 `1` 的子数组内部的索引值为 `1` 的元素。如果在 `fruits` 数组索引值 为 `1` 的位置不存在元素,会直接返回 `undefined`。如果 `fruits` 数组在索引值为 `1` 的位置存在元素,但是子数组在索引值为 `1` 的位置不存在元素,也会返回 `undefined`。 + +首先,我们尝试打印 `[['🍊', '🍌'], ['🍍']]` 的子数组 `['🍍']` 的第 2 个元素。这个子数组只包含一个元素,也就意味着在索引值为 `1` 的位置不存在元素,所以返回的是 `undefined`。 + +其次,我们在没有传入任何参数调用了 `getFruits` 函数,也就意味着形参 `fruits` 的默认值为`undefined`。因为我们选择性地链接了 `fruits` 在索引值为 `1` 的元素,因为在索引值为 `1` 的位置不存在元素,因此返回的是 `undefined`。 + +最后,我们尝试打印 `['🍍'], ['🍊', '🍌']` 的子数组 `['🍊', '🍌']` 的第 2 个元素。子数组索引值为 `1`的位置为 `🍌`,因此它被打印出了。 + +

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

+ +#### 答案:A + +我们设置 `calc` 变量为 `Calc` 类的一个新实例。然后,我们初始化一个 `Calc` 的新实例,而且调用了这个实例的 `increase` 方法。因为 count 属性是在 `Calc` class 的 constructor 内部的,所以 count 属性不会在 `Calc` 的原型链上共享出去。这就意味着 calc 实例的 count 值不会被更新,count 仍然是 `0`。 + +

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

+ +#### 答案:B + + `updateUser` 函数更新 user 的 `email` 和 `password` 属性的值,如果它们的值传入函数,函数返回的就是 `user` 对象。`updateUser` 函数的返回值是 `user` 对象,意味着 updatedUser 的值与 `user` 指向的是同一个 `user` 对象。`updatedUser === user` 为 `true`. + +

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

+ +#### 答案:C + +首先,我们在 fruit 数组上调用 `slice` 方法。slice 方法不会修改原始数组,但是会返回从数组切片下来的值:香蕉 emoji。 +其次,我们在 fruit 数组上调用 `splice` 方法。splice 方法会修改原始数组,也就意味着 fruit 数组此时为 `['🍊', '🍎']`。 +最后,我们在 fruit 数组上调用 `unshift` 方法,通过添加一个值的方式改变了原始数组,添加的是'🍇',它成为了数组的第一个元素。现在 fruit 数组的组成为 `['🍇', '🍊', '🍎']`。 + +

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

+ +#### 答案:B + +对象的键会被转换为字符串。 + +因为 `dog` 的值是一个对象,`animals[dog]` 实际上意味着我们创建了一个叫做 `"object Object"` 的属性来代表新的对象。`animals["object Object"]` 现在等于 `{ emoji: "🐶", name: "Mara"}`。 + +`cat` 也是一个对象,`animals[cat]` 实际上意味着我们在用新的 cat 的属性覆盖 `animals[``"``object Object``"``]` 的值。 + +打印 `animals[dog]`,实际上是`animals["object Object"]`,这是因为转化`dog`对象为一个字符串结果 `"object Object"`,所以返回 `{ emoji: "🐈", name: "Sara" }`。 + +

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

+ +#### 答案:A + +`updateEmail` 函数是一个箭头函数,它没有和 `user` 对象绑定。这就意味着 `this` 关键字不会引用到 `user` 对象,但是会引用到全局对象。`user` 对象内部的 `email` 的值不会更新。当打印 `user.email` 的时候,原始值 `my@email.com` 被返回。 + +

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

+ +#### 答案:D + + `Promise.all` 方法可以并行式运行 promise。如果其中一个 promise 失败了,`Promise.all` 方法会带上被 reject 的 promise 的值_rejects_。在这个例子中,`promise3` 带着 `"Third"` 值 reject。我们在调用 `runPromises` 时在 `runPromises` 函数内部的 `catch` 方法去捕获任意 error 从而捕获到被 reject 的值。因为 `promise3` 带着 `"Third"` 被 reject,所以只有 `"Third"` 打印。 + +

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

+ +#### 答案:C + + `fromEntries` 方法可以将二维数组转换为对象。在每个子数组的第一个元素是 key,在每个子数组的第二个元素是 value。在这个例子中,我们映射了 `keys` 数组,它返回了一个数组,数组的第一个元素为 keys 数组当前索引的值,第二个元素为 values 数组当前索引的值。 + +这样就创建了一个包含正确 keys 和 values 的子数组的数组,因此结果为`{ name: "Lydia", age: 22 }`。 + +

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

+ +#### 答案:C + + `address` 的默认值是一个空对象 `{}`。当我们设置 `member` 变量为 `createMember` 函数返回的对象,我们没有为 address 参数传值,意味着 address 的值为默认的空对象 `{}`。一个空对象是一个 truthy 值,意味着 `address ? address : null` 条件会返回 `true`。address 的值为空对象 `{}`。 + +

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

+ +#### 答案:B + + `if` 语句的条件判断 `!typeof randomValue` 的值是否等于 `"string"`。`!` 操作符将这个值转化为一个布尔值。如果值是 truthy 的话,返回值会是 `false`,如果值是 falsy,返回值会是 `true`。在这里,`typeof randomValue` 的返回值是一个 truthy 值 `"number"`,意味着 `!typeof randomValue` 的值是一个布尔值 `false`。 -对象默认并不是可迭代的。如果迭代规则被定义,则一个对象是可迭代的(An iterable is an iterable if the iterator protocol is present)。我们可以通过添加迭代器symbol `[Symbol.iterator]` 来定义迭代规则,其返回一个 generator 对象,比如说构建一个 generator 函数 `*[Symbol.iterator]() {}`。如果我们想要返回数组 `["Lydia Hallie", 21]`: `yield* Object.values(this)`,这个 generator 函数一定要 yield 对象 `person` 的`Object.values`。 + `!typeof randomValue === "string"` 总是返回 false,因为我们实际上是在执行 `false === "string"`。因为条件返回的是 `false`,所以 `else` 语句中的代码块会被运行,因此打印 `Yay it's a string!`。

diff --git a/zh-TW/README_zh-TW.md b/zh-TW/README_zh-TW.md new file mode 100644 index 00000000..b6bf9c06 --- /dev/null +++ b/zh-TW/README_zh-TW.md @@ -0,0 +1,5068 @@ +
+ +

JavaScript 進階題目列表

+--- + +我會在我的 [Instagram](https://www.instagram.com/theavocoder) 上發布關於 JavaScript 的複選題,同時也會更新到這個 Repo 當中。更新日期: 2020 年 06 月 12 日 + +從基礎到進階程度,測試你有多了解 JavaScript,不僅更新你的知識,更能幫助你的 coding 面試! +:muscle: :rocket: 我每週都會在這個 Repo 中更新新的題目。 + +答案在題目下方的摺疊區塊,點擊即可展開答案。祝你好運 :heart: + +歡迎和我聯繫!😊
+Instagram || Twitter || LinkedIn || Blog + +
+ +--- + +歡迎在項目中使用它們 😃 我 _真的_ 很感激這個 repo 的參考,我創造了問題和解釋(是的,我很傷心 lol),社區幫助我如此之多地維護和改進它!我很喜歡這個 repo。 💪🏼 謝謝你,祝你玩得開心! + +--- + +###### 1. 將會輸出什麽內容? + +```javascript +function sayHi() { + console.log(name) + console.log(age) + var name = 'Lydia' + let age = 21 +} + +sayHi() +``` + +- A: `Lydia` 和 `undefined` +- B: `Lydia` 和 `ReferenceError` +- C: `ReferenceError` 和 `21` +- D: `undefined` 和 `ReferenceError` + +
答案 +

+ +#### 答案:D + +在函式內部,我們首先透過 `var` 關鍵字宣告了 `name` 變數。這表示變數被提升了(記憶體位置在建立時期就被設置好了),直到程式執行到定義變數的那行之前,預設值都是 `undefined`。因為當我們印出 `name` 變數時,還沒有執行到定義變數的那一行程式碼,因此變數的值保持為 `undefined`。 + +透過 `let` 和 `const` 關鍵字宣告的變數也會提升,但是和 `var` 不同,它們不會被初始化,在我們初始化之前是不能訪問它們的,這個行為被稱之為暫時性死區。當我們嘗試在初始化之前訪問它們時,JavaScript 將會抛出一個 `ReferenceError` 錯誤。 + +

+
+ +--- + +###### 2. 將會輸出什麽內容? + +```javascript +for (var i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1) +} + +for (let i = 0; i < 3; i++) { + setTimeout(() => console.log(i), 1) +} +``` + +- A: `0 1 2` 和 `0 1 2` +- B: `0 1 2` 和 `3 3 3` +- C: `3 3 3` 和 `0 1 2` + +
答案 +

+ +#### 答案:C + +由於 JavaScript 的事件佇列(Event Queue),`setTimeout` 的 `callback` 會在*遍歷結束後*才執行。因為在第一個迴圈中,遍歷 `i` 是透過 `var` 關鍵字宣告的,`var` 屬於 Function scope(需要用 `function() {}` 才能將值鎖在作用域裡面) +,所以 `for` 迴圈會造成變數外流,變成全域變數。在遍歷過程中,我們透過一元運算子 `++` 來遞增 `i` 的值。當 `setTimeout` 的 `callback` 執行的時候,`i` 的值等於 3。 + +在第二個迴圈中,遍歷 `i` 是透過 `let` 關鍵字宣告的:透過 `let` 和 `const` 關鍵字的變數擁有塊級作用域(指的是任何在 `{}` 中的内容)。在每次的遍歷過程中,`i` 都有一個新值,每次遍歷時 `i` 值的作用域都在迴圈内。 + +

+
+ +--- + +###### 3. 將會輸出什麽內容? + +```javascript +const shape = { + radius: 10, + diameter() { + return this.radius * 2 + }, + perimeter: () => 2 * Math.PI * this.radius +} + +shape.diameter() +shape.perimeter() +``` + +- A: `20` and `62.83185307179586` +- B: `20` and `NaN` +- C: `20` and `63` +- D: `NaN` and `63` + +
答案 +

+ +#### 答案 B + +注意 `diameter` 的值是一個一般的函式,但是 `perimeter` 的值是一個箭頭函式。 + +對於箭頭函式,`this` 關鍵字指向的是它當前周圍作用域,這個行為和一般函式不同。這表示當我們呼叫 `perimeter` 時,`this` 不是指向 `shape` 物件,而是它的周圍作用域(在範例中是 `window`)。 + +在 `window` 中沒有 `radius` 這個屬性,因此回傳 `undefined`。 + +

+
+ +--- + +###### 4. 將會輸出什麽內容? + +```javascript ++true; +!"Lydia"; +``` + +- A: `1` and `false` +- B: `false` and `NaN` +- C: `false` and `false` + +
答案 +

+ +#### 答案:A + +一元運算子加號 `+`,嘗試將 boolean 布林值型別轉為 number 數字型別。`true` 轉為 number 數字型別的話為 `1`,`false` 爲 `0`。 + +字串型別 `'Lydia'` 是一個真值,我們實際上問的題目是:「這個真值的相反會是什麼?」,真值的相反,將得到 `false`。 + +

+ +
+ +--- + +###### 5. 哪一個是正確的描述? + +```javascript +const bird = { + size: 'small' +} + +const mouse = { + name: 'Mickey', + small: true +} +``` + +- A: `mouse.bird.size`是無效的 +- B: `mouse[bird.size]`是無效的 +- C: `mouse[bird["size"]]`是無效的 +- D: 以上三個選項都是有效的 + +
答案 +

+ +#### 答案:A + +在 JavaScript 中,所有物件的 keys 都是字串型別(除非是 Symbol 物件)。儘管我們或許不會定義它們為字串,但它們在底層總會被轉換爲字串。 + +當我們使用中括號時([]),JavaScript 會解譯語句。它首先看到中括號的第一個開始處 `[` 並繼續往下直到找到結束的中括號 `]`。只有這樣,它才能計算語句的值。 + +`mouse[bird.size]`:首先計算 `bird.size`,這會得到 `small`。`mouse["small"]` 得到 `true`。 + +使用點的語法的時候,上面這一切都不會發生。`mouse` 沒有 `bird` 這個 key,這就表示 `mouse.bird` 是 `undefined`。然後當我們使用點語法 `mouse.bird.size` 時,因為 `mouse.bird` 是 `undefined`,這也就變成了我們實際的語句是 `undefined.size`,而此行為是無效的,並會抛出一個錯誤 `Cannot read property "size" of undefined`。 + +

+
+ +--- + + +###### 6. 將會輸出什麽內容? + +```javascript +let c = { greeting: 'Hey!' } +let d + +d = c +c.greeting = 'Hello' +console.log(d.greeting) +``` + +- A: `Hello` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
答案 +

+ +#### 答案:A + +在 JavaScript 中,當設定兩個物件彼此相等時,它們會經由*引用(reference)*進行互動。 + +首先,變數 `c` 的值是一個物件。接下来,我們將 `d` 分配了一個和 `c` 物件相同的引用。 + + + +因此當我們改變其中一個物件時,其實是改變了所有的物件的同一個引用的內容。 + +

+
+ +--- + +###### 7. 將會輸出什麽內容? + +```javascript +let a = 3 +let b = new Number(3) +let c = 3 + +console.log(a == b) +console.log(a === b) +console.log(b === c) +``` + +- A: `true` `false` `true` +- B: `false` `false` `true` +- C: `true` `false` `false` +- D: `false` `true` `true` + +
答案 +

+ +#### 答案:C + +`new Number()` 是一個内建的函式建構子。它雖然看起來像是個 number,但它實際上並非真正的 number:它有一堆額外的功能,而且它是一個物件。 + +當我們使用 `==` 運算子的時候,它只會檢查兩者是否擁有有相同的*值*。因為它們的值都是 `3`,因此回傳 `true`。 + +然後,當我們使用 `===` 運算子時,兩者的值以及*型別*都必須是相同的。`new Number()` 是一個物件型別而不是 number(一般型別),因此回傳 `false`。 + +

+
+ +--- + +###### 8. 將會輸出什麽內容? + +```javascript +class Chameleon { + static colorChange(newColor) { + this.newColor = newColor + return this.newColor + } + + constructor({ newColor = 'green' } = {}) { + this.newColor = newColor + } +} + +const freddie = new Chameleon({ newColor: 'purple' }) +freddie.colorChange('orange') +``` + +- A: `orange` +- B: `purple` +- C: `green` +- D: `TypeError` + +
答案 +

+ +#### 答案:D + +`colorChange` 是一個靜態方法。靜態方法被設計爲只能被創造它們的建構子使用(也就是 `Chameleon` 中的 `constructor`),並且不能傳遞給實例。因為 `freddie` 是一個實例,而靜態方法不能被實例使用,因此會抛出 `TypeError` 錯誤。 + +

+
+ +--- + +###### 9. 將會輸出什麽內容? + +```javascript +let greeting +greetign = {} // 手殘打錯變數名稱! +console.log(greetign) +``` + +- A: `{}` +- B: `ReferenceError: greetign is not defined` +- C: `undefined` + +
答案 +

+ +#### 答案:A + +程式碼印出了一個物件,這是因為我們在全域物件上建立了一個空物件!當我們將 `greeting` 寫錯成 `greetign` 時,JS 解譯器實際上將它視爲 `global.greetign = {}`(或者在瀏覽器中視為 `window.greetign = {}`)。 + +為了避免這個狀況,我們可以使用 `"use strict"`,來確保當你宣告變數時,必須賦值。 + +

+
+ +--- + +###### 10. 當我們這麼做時,會發生什麼事? + +```javascript +function bark() { + console.log('Woof!') +} + +bark.animal = 'dog' +``` + +- A: 正常運作! +- B: `SyntaxError`. 你不能透過這種方式在函式中新增屬性。 +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案:A + +這在 JavaScript 中是可以的,因爲函式是物件!(除了基本型別之外其他都是物件) + +函式是一個特殊的物件,函式是一個擁有屬性的物件,屬性也可被使用、呼叫的。 + +

+
+ +--- + +###### 11. 將會輸出什麽內容? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName; + this.lastName = lastName; +} + +const member = new Person("Lydia", "Hallie"); +Person.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +} + +console.log(member.getFullName()); +``` + +- A: `TypeError` +- B: `SyntaxError` +- C: `Lydia Hallie` +- D: `undefined` `undefined` + +
答案 +

+ +#### 答案:A + +你可以為一般物件新增屬性,但建構函式(constructor)無法透過上面的方式來新增屬性。若你想一次性在所有實例上都新增某個屬性,要使用原型的方式。因此本例中,使用以下的方式: + +```js +Person.prototype.getFullName = function () { + return `${this.firstName} ${this.lastName}`; +} +``` + +這樣一來,`member.getFullName()` 就能有效。這樣做有什麼好處?假設我們真的能如題將這個方法新增到建構函式本身,並不是每個 `Person` 實例都需要這個方法,但每個實例卻仍然擁有該属性,代表著這將佔據每個實例的記憶體,造成大量的記憶體空間因此浪費掉了。相反,如果我們只將它新增在原型中,那麼它只存在記憶體中的一個位置,而所有實例都可以使用它! + +

+
+ +--- + +###### 12. 將會輸出什麽內容? + +```javascript +function Person(firstName, lastName) { + this.firstName = firstName + this.lastName = lastName +} + +const lydia = new Person('Lydia', 'Hallie') +const sarah = Person('Sarah', 'Smith') + +console.log(lydia) +console.log(sarah) +``` + +- A: `Person {firstName: "Lydia", lastName: "Hallie"}` and `undefined` +- B: `Person {firstName: "Lydia", lastName: "Hallie"}` and `Person {firstName: "Sarah", lastName: "Smith"}` +- C: `Person {firstName: "Lydia", lastName: "Hallie"}` and `{}` +- D:`Person {firstName: "Lydia", lastName: "Hallie"}` and `ReferenceError` + +
答案 +

+ +#### 答案:A + +對 `sarah` 而言,我們沒有使用 `new` 關鍵字。當使用 `new` 時,`this` 引用我們建立的空物件。沒有使用 `new` 的時候,`this` 引用的是**全域物件**(global object)。 + +我們會說 `this.firstName` 等於 `"Sarah"`,而 `this.lastName` 等於 `"Smith"`。實際上我們做的是,定義了 `global.firstName = 'Sarah'` 和 `global.lastName = 'Smith'`。而 `sarah` 本身是 `undefined`,因為 `Person` 這個函式本身並沒有回傳值。 + +

+
+ +--- + +###### 13. 事件傳播的三個階段分別是? + +- A: Target > Capturing > Bubbling +- B: Bubbling > Target > Capturing +- C: Target > Bubbling > Capturing +- D: Capturing > Target > Bubbling + +
答案 +

+ +#### 答案:D + +先捕獲,再冒泡!在**捕獲**(capturing)階段中,事件從祖先元素向下傳播到目標元素。當事件到達**目標**(target)元素後,**冒泡**(bubbling)才開始。 + + + +

+
+ +--- + +###### 14. 所有物件都有原型。 + +- A: true +- B: false + +
答案 +

+ +#### 答案:B + +除了**基本物件**(base object,使用 `new` 關鍵字建立的物件)以外,所有物件都有原型。基本物件可以使用一些方法和属性,比如 `.toString`,這就是為什麼你可以使用內建的 JavaScript 方法!所有這類在原型上的方法都是可被使用的。雖然 JavaScript 不能直接在物件上找到這些方法,但 JavaScript 會沿著原型鍊找到它們,以便使用。 + +

+
+ +--- + +###### 15. 將會輸出什麽內容? + +```javascript +function sum(a, b) { + return a + b +} + +sum(1, '2') +``` + +- A: `NaN` +- B: `TypeError` +- C: `"12"` +- D: `3` + +
答案 +

+ +#### 答案:C + +JavaScript 是一個**動態型別語言**:我們不指定變數的型別。值可以在你不知道的情况下自動轉換成另一種型別,稱為**隱含式轉型**(implicit type coercion)。**Coercion** 是指將一種型別轉換成另一種型別。 + +在此範例中,JavaScript 將數字型別 `1` 轉換為字串型別,以便函式能回傳一個有意義的值。數字型別(`1`)和字串型別(`'2'`)相加的時候,該數字會被視為字串。我們也能連接不同的字串,比如 `"Hello" + "World"`,而此例是 `"1" + "2"`,它將回傳 `"12"`。 + +

+
+ +###### 16. 將會輸出什麽內容? + +```javascript +let number = 0; +console.log(number++); +console.log(++number); +console.log(number); +``` + +- A: `1` `1` `2` +- B: `1` `2` `2` +- C: `0` `2` `2` +- D: `0` `1` `2` + +
答案 +

+ +#### 答案:C + +一元運算子 `++` 加在變數後方: + +1. 回傳值 (這個值是 `0`) +2. 新增值 (變數 `number` 的值現在是 `1`) + +一元運算子 `++` 加在變數前方: + +1. 新增值 (變數 `number` 的值現在是 `2`) +2. 回傳值 (這個值是 `2`) + +因此答案是 `0 2 2`. + +

+
+ +--- + +###### 17. 將會輸出什麽內容? + +```javascript +function getPersonInfo(one, two, three) { + console.log(one); + console.log(two); + console.log(three); +} + +const person = 'Lydia'; +const age = 21; + +getPersonInfo`${person} is ${age} years old`; +``` + +- A: `"Lydia"` `21` `["", " is ", " years old"]` +- B: `["", " is ", " years old"]` `"Lydia"` `21` +- C: `"Lydia"` `["", " is ", " years old"]` `21` + +
答案 +

+ +#### 答案:B + +若你使用標籤樣板字面值(Tagged template literals),第一個參數的值永遠會是一個裝載字串的陣列,函式中的剩下的參數會取得表達式中傳進的變數(`person`、`age`)的值(`'Lydia'`、`21`)! + +

+
+ +--- + +###### 18. 將會輸出什麽內容? + +```javascript +function checkAge(data) { + if (data === { age: 18 }) { + console.log('You are an adult!'); + } else if (data == { age: 18 }) { + console.log('You are still an adult.'); + } else { + console.log(`Hmm.. You don't have an age I guess`); + } +} + +checkAge({ age: 18 }); +``` + +- A: `You are an adult!` +- B: `You are still an adult.` +- C: `Hmm.. You don't have an age I guess` + +
答案 +

+ +#### 答案:C + +驗證相等,一般型別只比較「值」,物件型別則是比較他們的「參考」。JavaScript 會確認不同物件的參考是否指向同一個記憶體位置。 + +題目中,我們比較的兩個物件擁有不同的記憶體位置:一個物件是作為參數傳遞的物件,它的記憶體位置與另一個拿來判斷是否相等的物件並不相同。 + +這就是 `{ age: 18 } === { age: 18 }` 與 `{ age: 18 } == { age: 18 }` 會回傳 `false` 的原因。 + +

+
+ +--- + +###### 19. 將會輸出什麽內容? + +```javascript +function getAge(...args) { + console.log(typeof args); +} + +getAge(21); +``` + +- A: `"number"` +- B: `"array"` +- C: `"object"` +- D: `"NaN"` + +
答案 +

+ +#### 答案:C + +其餘參數(`...args`)會蒐集傳進來剩下來未使用的參數,成為一個「陣列」。陣列的型別是「物件」,所以透過 `typeof args` 將會回傳該值的型別,將是 `"object"`。 + +

+
+ +--- + +###### 20. 將會輸出什麽內容? + +```javascript +function getAge() { + 'use strict'; + age = 21; + console.log(age); +} + +getAge(); +``` + +- A: `21` +- B: `undefined` +- C: `ReferenceError` +- D: `TypeError` + +
答案 +

+ +#### 答案:C + +`"use strict"` 可以避免妳意外地宣告全區域變數。使用 `"use strict"` 時,我們若沒有宣告 `age` 這個變數,就直接賦值的話,會拋出 `ReferenceError`,若沒有使用 `"use strict"`,屬性 `age` 就會新增到全域物件上(瀏覽器上的全域物件是 `window`)。 + +

+
+ +--- + +###### 21. `sum` 的值會是? + +```javascript +const sum = eval('10*10+5'); +``` + +- A: `105` +- B: `"105"` +- C: `TypeError` +- D: `"10*10+5"` + +
答案 +

+ +#### 答案:A + +`eval` 會去執行傳進去的「字串」。如果該字串是一個表達式,如題目中的程式碼,那麼 `eval` 會自動執行該表達式 `10 * 10 + 5`,所以答案會是 `105`。 + +

+
+ +--- + +###### 22. cool_secret 這個資料儲存在瀏覽器,存活時間有多久? + +```javascript +sessionStorage.setItem('cool_secret', 123); +``` + +- A: 永遠都可以,資料不會不見。 +- B: 使用者關閉頁籤後,資料才會失效。 +- C: 使用者要關閉一整個瀏覽器,資料才會失效,單純關閉資料不會造成資料消失。 +- D: 使用者關閉電腦後。 + +
答案 +

+ +#### 答案:B + +儲存在 `sessionStorage` 的資料會在使用者「關閉頁籤」後消失。 + +若是使用 `localStorage` 來儲存資料的話,資料則會永遠存在瀏覽器端,直到觸發了 `localStorage.clear()` 才可以清除資料。 + +

+
+ +--- + +###### 23. 將會輸出什麽內容? + +```javascript +var num = 8; +var num = 10; + +console.log(num); +``` + +- A: `8` +- B: `10` +- C: `SyntaxError` +- D: `ReferenceError` + +
答案 +

+ +#### 答案:B + +使用 `var` 關鍵字重複宣告的變數,該值會以最新賦予的值作為它的「值」。這件事情在 `let` or `const` 不會發生,因為這兩個關鍵字所宣告的變數作用域是塊級作用域(block-scoped)。 + +

+
+ +--- + +###### 24. 將會輸出什麽內容? + +```javascript +const obj = { 1: 'a', 2: 'b', 3: 'c' }; +const set = new Set([1, 2, 3, 4, 5]); + +obj.hasOwnProperty('1'); +obj.hasOwnProperty(1); +set.has('1'); +set.has(1); +``` + +- A: `false` `true` `false` `true` +- B: `false` `true` `true` `true` +- C: `true` `true` `false` `true` +- D: `true` `true` `true` `true` + +
答案 +

+ +#### 答案:C + +除了 `Symbol` 以外的物件的 `key` 在底層都是字串類別,即使你建立該物件屬性時,並不是以字串來建立的,所以 `obj.hasOwnProperty('1')` 會回傳 `true`。不過 `set` 不是這樣的規則,在題目中的 `set` 並沒有字串 `'1'` 這個屬性名稱,所以 `set.has('1')` 會回傳 `false`,不過是有數字類別 `1` 的屬性值,`set.has(1)` 將會回傳 `true`。 + +

+
+ +--- + +###### 25. 將會輸出什麽內容? + +```javascript +const obj = { a: 'one', b: 'two', a: 'three' }; +console.log(obj); +``` + +- A: `{ a: "one", b: "two" }` +- B: `{ b: "two", a: "three" }` +- C: `{ a: "three", b: "two" }` +- D: `SyntaxError` + +
答案 +

+ +#### 答案:C + +若物件中的屬性有重複名稱者,第一個屬性會保持它的位置,但值會被最後一個重複屬性名稱的值給取代。 + +

+
+ +--- + +###### 26. JavaScript 在全域執行環境為你做了兩件事:全域物件和 this 關鍵字。 + +- A: true +- B: false +- C: it depends + +
答案 +

+ +#### 答案:A + +基本执行上下文是全局执行上下文:它是代码中随处可访问的内容。 +基底的執行環境是全域的:代表它在程式碼中,可被隨處使用。 + +

+
+ +--- + +###### 27. 將會輸出什麽內容? + +```javascript +for (let i = 1; i < 5; i++) { + if (i === 3) continue; + console.log(i); +} +``` + +- A: `1` `2` +- B: `1` `2` `3` +- C: `1` `2` `4` +- D: `1` `3` `4` + +
答案 +

+ +#### 答案:C + +當 `if` 條件成立時會回傳 `true`,執行 `continue` 語句,代表忽略本次迭代(`console.log(i)`)。 + +

+
+ +--- + +###### 28. 將會輸出什麽內容? + +```javascript +String.prototype.giveLydiaPizza = () => { + return 'Just give Lydia pizza already!'; +}; + +const name = 'Lydia'; + +console.log(name.giveLydiaPizza()) +``` + +- A: `"Just give Lydia pizza already!"` +- B: `TypeError: not a function` +- C: `SyntaxError` +- D: `undefined` + +
答案 +

+ +#### 答案:A + +`String` 是內建的建構函式,我們可以向它新增属性。我只是在它的原型中加上一個方法。基本型別字串被自動轉換成字串物件,由字串原型函式生成。因此,所有 string(string 物件)都可以使用 `giveLydiaPizza` 方法! + +

+
+ +--- + +###### 29. 將會輸出什麽內容? + +```javascript +const a = {}; +const b = { key: 'b' }; +const c = { key: 'c' }; + +a[b] = 123; +a[c] = 456; + +console.log(a[b]); +``` + +- A: `123` +- B: `456` +- C: `undefined` +- D: `ReferenceError` + +
答案 +

+ +#### 答案:B + +物件的 key 自動轉為字串型別。我們正嘗試將物件 `b` 的 key 設為物件 `a` 的 key,其值爲 `123`。 + +然而,當物件「字串化」,它會變成 `"[object Object]"`。所以這裡的意思是,`a["[object Object]"] = 123`。然後,我們又再做了一次一樣的事情,`c` 也是隱式的物件字串化,所以,`a["[object Object]"] = 456`。 + +最後,我們輸出 `a[b]`,也就是 `a["[object Object]"]`。之前剛賦值爲 `456`,將回傳 `456`。 + +

+
+ +--- + +###### 30. 將會輸出什麽內容? + +```javascript +const foo = () => console.log('First'); +const bar = () => setTimeout(() => console.log('Second')); +const baz = () => console.log('Third'); + +bar(); +foo(); +baz(); +``` + +- A: `First` `Second` `Third` +- B: `First` `Third` `Second` +- C: `Second` `First` `Third` +- D: `Second` `Third` `First` + +
答案 +

+ +#### 答案:B + +我們有一個 `setTimeout` 函式,首先呼叫它。然而,它的執行順序是最後執行的。 + +因為在瀏覽器中,我們除了有執行引擎,還有一個 `WebAPI`。`WebAPI` 提供了 `setTimeout` 函式,也包含其他的,例如 DOM。 + +在『callback』推送到 `WebAPI` 後,`setTimeout` 函式本身(不是回呼函式)將從堆疊(`stack`)中彈出。 + + + +現在,`foo` 被呼叫,印出 `"First"`。 + + + +`foo` 從堆疊中彈出,`baz` 被呼叫,印出 `"Third"`。 + + + +WebAPI 不能隨時向堆疊内新增内容。相反,它會將回呼函式彈到名爲『`queue`』的地方。 + + + +這就是事件迴圈(`Event Loop`)的流程,了解**事件迴圈**堆疊與任務佇列的運作模式。如果堆疊是空的,它接受任務佇列上的第一个元素,推入堆疊中。 + + + +`bar` 被呼叫,印出 `"Second"`,然後它被彈出堆疊。 + +

+
+ +--- + +###### 31. 點擊按鈕時,event.target 指的是哪個元件? + +```html +
+
+ +
+
+``` + +- A: 第一層的 `div` +- B: 第二層的 `div` +- C: `button` 本身 +- D: 一個包含此巢狀元件的陣列。 + +
答案 +

+ +#### 答案:C + +產生事件 (event) 的元件即為此事件的 target,您可以透過 `event.stopPropagation` 來停止事件的冒泡 (bubbling) + +

+
+ +--- + +###### 32. 點擊標籤 p(paragraph) 時,將會輸出什麼內容? + +```html +
+

+ Click here! +

+
+``` + +- A: `p` `div` +- B: `div` `p` +- C: `p` +- D: `div` + +
答案 +

+ +#### 答案:A + +輸出內容是 `p` 及 `div`。在事件傳播 (event propagation) 期間,分為三個階段:捕獲 (capturing),目標 (target) 和冒泡 (bubbling)。 +預設情況下,事件處理 (event handlers) 在冒泡階段執行(除非您將 useCapture 設置為 true)。它從巢狀元素的最深層向外層。 + +

+
+ +--- + +###### 33. 將會輸出什麽內容? + +```javascript +const person = { name: 'Lydia' }; + +function sayHi(age) { + return `${this.name} is ${age}`; +} + +console.log(sayHi.call(person, 21)); +console.log(sayHi.bind(person, 21)); +``` + +- A: `undefined is 21` `Lydia is 21` +- B: `function` `function` +- C: `Lydia is 21` `Lydia is 21` +- D: `Lydia is 21` `function` + +
答案 +

+ +#### 答案:D + +通過 `.call` 及 `.bind`,我們可以將想要 `this` 關鍵字引用的物件傳遞給它。 +然而,`.call` 會 _立即執行_! `.bind.` 則是會回傳一份函式 (function) 的 _複製_ 且不會立即執行。 + +

+
+ +--- + +###### 34. 將會輸出什麽內容? + +```javascript +function sayHi() { + return (() => 0)(); +} + +console.log(typeof sayHi()); +``` + +- A: `"object"` +- B: `"number"` +- C: `"function"` +- D: `"undefined"` + +
答案 +

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

+
+ +--- + +###### 35. 下列項目哪些是 falsy? + +```javascript +0; +new Number(0); +(''); +(' '); +new Boolean(false); +undefined; +``` + +- A: `0`, `''`, `undefined` +- B: `0`, `new Number(0)`, `''`, `new Boolean(false)`, `undefined` +- C: `0`, `''`, `new Boolean(false)`, `undefined` +- D: All of them are falsy + +
答案 +

+ +#### 答案:A + +只有八個值是 falsy + +- `undefined` +- `null` +- `NaN` +- `false` +- `''` (空字串) +- `0` +- `-0` +- `0n` (BigInt(0)) + +函式建構式 (Function constructors) 如 `new Number` 和 `new Boolean` 都為 truthy。 + +

+
+ +--- + +###### 36. 將會輸出什麽內容? + +```javascript +console.log(typeof typeof 1); +``` + +- A: `"number"` +- B: `"string"` +- C: `"object"` +- D: `"undefined"` + +
答案 +

+ +#### 答案:B + +`typeof 1` 回傳 `"number"` +`typeof "number"` 回傳 `"string"` + +

+
+ +--- + +###### 37. 將會輸出什麽內容? + +```javascript +const numbers = [1, 2, 3]; +numbers[10] = 11; +console.log(numbers); +``` + +- A: `[1, 2, 3, 7 x null, 11]` +- B: `[1, 2, 3, 11]` +- C: `[1, 2, 3, 7 x empty, 11]` +- D: `SyntaxError` + +
答案 +

+ +#### 答案:C + +當您設置的元素其位置大過陣列長度時,JavaScript 會建立一個叫做 "empty slots" 的物件,它們的值實際上為 `undefined`。 + +但您會看到類似的輸出內容 : `[1, 2, 3, 7 x empty, 11]`。實際執行環境會使其輸出內容略微不同 (瀏覽器,node... 等) + +

+
+ +--- + + +###### 38. 將會輸出什麽內容? + +```javascript +(() => { + let x, y; + try { + throw new Error(); + } catch (x) { + (x = 1), (y = 2); + console.log(x); + } + console.log(x); + console.log(y); +})(); +``` + +- A: `1` `undefined` `2` +- B: `undefined` `undefined` `undefined` +- C: `1` `1` `2` +- D: `1` `undefined` `undefined` + +
答案 +

+ +#### 答案:A + +程式中的 `catch` 區塊捕獲了一個例外情況且賦殖予 argument `x`。這個 `x` 是在區塊內產生的,其有效範圍只在區塊內 (block-scoped),它跟 `console.log` 中所傳入的 `x` 並不是同一個。 + +接著我們將此區塊變數 `x` 設置為等於 `1`,並設置變數 `y` 的值,現在我們 console.log 區塊變數 `x`,無意外地它輸出 `1`。 + +而在 `catch` 區塊之外的 `x` 仍然是 `undefined` 且 `y` 是 `2`。因此當我們想在 `catch` 區塊之外使用 `console.log(x)` 時,它回傳 `undefined`,而 `y` 回傳 `2`。 + +

+
+ +--- + +###### 39. 關於 JavaScript 的敘述何者正確? + +- A: JavaScript 的世界中不是 primitive 就是 object +- B: JavaScript 的世界中不是 function 就是 object +- C: JavaScript 的世界中只有 object +- D: JavaScript 的世界中不是 number 就是 object + +
答案 +

+ +#### 答案:A + +JavaScript 只有 primitive types 和 objects. + +而 Primitive types 包含 `boolean`, `null`, `undefined`, `bigint`, `number`, `string`, 和 `symbol`. + +Primitive 不同於 object 的是它沒有任何的屬性 (properties) 和方法 (methods); 沒有方法的情況下為何 `'foo'.toUpperCase()` (string) 是輸出 `'FOO'` 而不是 `TypeError` ? +這是因為當您嘗試訪問 primitive types (例如字串) 的屬性或方法時,JavaScript 會使用其中一個 wrapper classes 包裝該 primitive type。 + +例如使用了 `String` 包裝 primitive type `string`,接著在 expression 被 evaluates 後拋棄該包裝。所有 primitives 除了 `null` 和 `undefined` 外都是遵循此行為。 + +

+
+ +--- + +###### 40. 將會輸出什麽內容? + +```javascript +[[0, 1], [2, 3]].reduce( + (acc, cur) => { + return acc.concat(cur); + }, + [1, 2], +); +``` + +- A: `[0, 1, 2, 3, 1, 2]` +- B: `[6, 1, 2]` +- C: `[1, 2, 0, 1, 2, 3]` +- D: `[1, 2, 6]` + +
答案 +

+ +#### 答案:C + +`[1, 2]` 為初始值,同時也是第一個 `acc`。在第一輪中,`acc` 是 `[1,2]` 且 `cur` 是 `[0, 1]`,兩陣列連接後的結果是 `[1, 2, 0, 1]`。 + +接著 `[1, 2, 0, 1]` 是 `acc` 且 `[2, 3]` 是 `cur`,兩陣列連接後的結果是 `[1, 2, 0, 1, 2, 3]`。 + +

+
+ +--- + +###### 41. 將會輸出什麽內容? + +```javascript +!!null; +!!''; +!!1; +``` + +- A: `false` `true` `false` +- B: `false` `false` `true` +- C: `false` `true` `true` +- D: `true` `true` `false` + +
答案 +

+ +#### 答案:B + +`null` 是 falsy. `!null` 回傳 `true`. `!true` 回傳 `false`. + +`""` 是 falsy. `!""` 回傳 `true`. `!true` 回傳 `false`. + +`1` 是 truthy. `!1` 回傳 `false`. `!false` 回傳 `true`. + +

+
+ +--- + +###### 42. 在瀏覽器中 `setInterval` 方法會回傳什麼? + +```javascript +setInterval(() => console.log('Hi'), 1000); +``` + +- A: 一個唯一的 id +- B: 指定的毫秒數 +- C: 被傳遞的函式 +- D: `undefined` + +
答案 +

+ +#### 答案:A + +會回傳一個唯一的 id,並可用於 `clearInterval()` 以清除該 interval。 + +

+
+ +--- + +###### 43. 將會回傳何種結果? + +```javascript +[...'Lydia']; +``` + +- A: `["L", "y", "d", "i", "a"]` +- B: `["Lydia"]` +- C: `[[], "Lydia"]` +- D: `[["L", "y", "d", "i", "a"]]` + +
答案 +

+ +#### 答案:A + +字串 (string) 類別是可以被迭代的 (iterable),展開運算子 (spread operator) 將可迭代的字元 (character) 映射 (map) 置一個元素 (element) 上。 + +

+
+ +--- + +###### 44. 將會輸出什麽內容? + +```javascript +function* generator(i) { + yield i; + yield i * 2; +} + +const gen = generator(10); + +console.log(gen.next().value); +console.log(gen.next().value); +``` + +- A: `[0, 10], [10, 20]` +- B: `20, 20` +- C: `10, 20` +- D: `0, 10 and 10, 20` + +
答案 +

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

+
+ +--- + +###### 45. 將會回傳何種結果? + +```javascript +const firstPromise = new Promise((res, rej) => { + setTimeout(res, 500, 'one'); +}); + +const secondPromise = new Promise((res, rej) => { + setTimeout(res, 100, 'two'); +}); + +Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); +``` + +- A: `"one"` +- B: `"two"` +- C: `"two" "one"` +- D: `"one" "two"` + +
答案 +

+ +#### 答案:B + +當我們向 Promise.race 方法傳遞多個 promise 時,它將 resolves / rejects _最先的_ promise。 +在 setTimeout 方法中,我們傳遞了一個計時器:第一個 promise(firstPromise)為 500 毫秒,第二個 promise(secondPromise)為 100 毫秒。這意味著 "secondPromise" 將先用 "two" 的值進行 resolves。現在,`res` 擁有 'two' 的值且該值被 console.log。 + +

+
+ +--- + +###### 46. 將會輸出什麽內容? + +```javascript +let person = { name: 'Lydia' }; +const members = [person]; +person = null; + +console.log(members); +``` + +- A: `null` +- B: `[null]` +- C: `[{}]` +- D: `[{ name: "Lydia" }]` + +
答案 +

+ +#### 答案:D + +首先,我們宣告一個物件變數 `person` 包含 `name` 屬性以及值 `Lydia`。 + + + +接著我們宣告另一個陣列變數 `members`。我們將該陣列的第一個元素設置等於 `person` 變數的值。 +當我們將它們設置為相等時,物件透過 _reference_ 互相關聯。當我們將一個物件變數的 reference 賦值給另一個變數時,實際上我們是 _複製_ 該 reference (它們沒有 _相同_ 的 reference !) + + + +接著我們將變數 `person` 賦予 `null`。 + + + +我們僅修改變數 `person` 的值,並無修改陣列中的第一個元素。 +基於該元素有份不同的 reference (一份複製的),故 `members` 陣列中第一位元素仍保有對物件的指向,於是當我們 console.log `members` 陣列時,輸出內容為物件。 + +

+
+ +--- + +###### 47. 將會輸出什麽內容? + +```javascript +const person = { + name: 'Lydia', + age: 21, +}; + +for (const item in person) { + console.log(item); +} +``` + +- A: `{ name: "Lydia" }, { age: 21 }` +- B: `"name", "age"` +- C: `"Lydia", 21` +- D: `["name", "Lydia"], ["age", 21]` + +
答案 +

+ +#### 答案:B + +通過 `for-in` 循環,我們可以遍歷物件的鍵,在這個題目中的鍵是 `name` 和 `age`。在內部,物件鍵是字串 (strings)(如果它們不是 Symbol)。 +在每次循環中,我們將 `item` 的值設置為等於其迭代的當前鍵。第一輪循環中,`item` 等於 `name`,並輸出內容。接著,`item` 等於 `age`,並輸出內容。 + +

+
+ +--- + +###### 48. 將會輸出什麽內容? + +```javascript +console.log(3 + 4 + '5'); +``` + +- A: `"345"` +- B: `"75"` +- C: `12` +- D: `"12"` + +
答案 +

+ +#### 答案:B + +運算子關聯性是編譯器計算表達式的順序,從左到右或從右到左。僅適用於所有運算子具有 _相同_ 優先級時,才會發生這種情況。 +在這裡我們只有一種類型的運算子:+。而其關聯性是從左到右。 + +首先計算 `3 + 4`。結果為數字 7。 + +由於強制 (coercion) ,`7 +'5'` 會導致結果為 `75`。JavaScript 將數字 `7` 轉換型態成字串,請參閱問題 15。我們可以使用 `+` 運算子將兩個字串連接起來。`7` + `5` 產生 `75`。 + +

+
+ +--- + +###### 49. `num` 的值會是什麼? + +```javascript +const num = parseInt('7*6', 10); +``` + +- A: `42` +- B: `"42"` +- C: `7` +- D: `NaN` + +
答案 +

+ +#### 答案:C + +僅會回傳字串中的第一個數字。基於 _radix_ (第二個參數,用於指定我們要將其解析為哪種類型的數字:以 10 為基數,十六進制,八進制,二進制等),`parseInt` 檢查字串中的字元是否有效。 +一旦遇到基數中無效數字的字元,它將停止解析並忽略以下字元。 + +`*` 不是合法的 `number`,所以程式僅將字串形態的 `"7"` 轉換至 decimal 形態的 `7`,故 `num` 現在的值為 `7`。 + +

+
+ +--- + +###### 50. 將會輸出什麽內容? + +```javascript +[1, 2, 3].map(num => { + if (typeof num === 'number') return; + return num * 2; +}); +``` + +- A: `[]` +- B: `[null, null, null]` +- C: `[undefined, undefined, undefined]` +- D: `[ 3 x empty ]` + +
答案 +

+ +#### 答案:C + +當對陣列做映射 (map) 時,`num` 的值等同於它當前正在循環的元素。在這種情況中元素均為 numbers,所以條件式 `typeof num === "number"` 會回傳 `true` 的值。 +map 函式會建立一個新陣列,並插入該函式回傳的值。 + +但是我們不回傳任何值。當我們不從函式回傳值時,函式將回傳 `undefined`。由於陣列中的每個元素都會呼叫該函式,因此對於每個元素,我們都回傳 `undefined`。 + +

+
+ +--- + +###### 51. 將會輸出什麽內容? + +```javascript +function getInfo(member, year) { + member.name = 'Lydia'; + year = '1998'; +} + +const person = { name: 'Sarah' }; +const birthYear = '1997'; + +getInfo(person, birthYear); + +console.log(person, birthYear); +``` + +- A: `{ name: "Lydia" }, "1997"` +- B: `{ name: "Sarah" }, "1998"` +- C: `{ name: "Lydia" }, "1998"` +- D: `{ name: "Sarah" }, "1997"` + +
答案 +

+ +#### 答案:A + +參數是透過 _value_ 傳遞,除非它們是一個物件 (object),物件則由透過 _reference_ 傳遞。`birthYear` 是透過值傳遞的,因為它是字串不是物件。當我們按值傳遞參數時,將建立該值的 _copy_ (請參閱問題 46)。 + +變數 `birthYear` 具有對值 `1997` 的 reference。參數 `year` 也有對值 `1997` 的 reference,但與變數 `birthYear` 所 reference 的不同。 +因此當我們通過將 `year` 設置為等於 `1998` 來更新 `year` 的值時,我們僅更新了 `year` 的值。`birthYear` 仍然等於 `"1997"`。 + +`person` 的值是一個物件。參數 `member` 具有(複製的)reference 指向 _相同_ 物件。 +因此當我們修改物件 `member` 的屬性時,`person` 的值也會被修改,因為它們都 reference 了相同的物件。`person` 的 `name` 屬性現在等於值 `"Lydia"`。 + +

+
+ +--- + +###### 52. 將會輸出什麽內容? + +```javascript +function greeting() { + throw 'Hello world!'; +} + +function sayHi() { + try { + const data = greeting(); + console.log('It worked!', data); + } catch (e) { + console.log('Oh no an error:', e); + } +} + +sayHi(); +``` + +- A: `It worked! Hello world!` +- B: `Oh no an error: undefined` +- C: `SyntaxError: can only throw Error objects` +- D: `Oh no an error: Hello world!` + +
答案 +

+ +#### 答案:D + +使用 `throw` 語句,我們可以建立自定義的錯誤。使用此語句,您可以觸發例外 (exception)。例外可以是 `string`,`number`,`boolean` 或 `object`。 +在這種情況下,我們的例外是字串 `Hello world`。 + +通過 `catch` 語句,我們可以指定如果在 `try` 的程式區塊中拋出例外時該怎麼辦。例如拋出例外:字串 `'Hello world'`。 +現在,`e` 等於我們記錄的字串。因此輸出結果將會是 `'Oh an error: Hello world'`。 + +

+
+ +--- + +###### 53. 將會輸出什麽內容? + +```javascript +function Car() { + this.make = 'Lamborghini'; + return { make: 'Maserati' }; +} + +const myCar = new Car(); +console.log(myCar.make); +``` + +- A: `"Lamborghini"` +- B: `"Maserati"` +- C: `ReferenceError` +- D: `TypeError` + +
答案 +

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

+
+ +--- + +###### 54. 將會輸出什麽內容? + +```javascript +(() => { + let x = (y = 10); +})(); + +console.log(typeof x); +console.log(typeof y); +``` + +- A: `"undefined", "number"` +- B: `"number", "number"` +- C: `"object", "number"` +- D: `"number", "undefined"` + +
答案 +

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

+
+ +--- + +###### 55. 將會輸出什麽內容? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +} + +Dog.prototype.bark = function() { + console.log(`Woof I am ${this.name}`); +}; + +const pet = new Dog('Mara'); + +pet.bark(); + +delete Dog.prototype.bark; + +pet.bark(); +``` + +- A: `"Woof I am Mara"`, `TypeError` +- B: `"Woof I am Mara"`, `"Woof I am Mara"` +- C: `"Woof I am Mara"`, `undefined` +- D: `TypeError`, `TypeError` + +
答案 +

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

+
+ +--- + +###### 56. 將會輸出什麽內容? + +```javascript +const set = new Set([1, 1, 2, 3, 4]); + +console.log(set); +``` + +- A: `[1, 1, 2, 3, 4]` +- B: `[1, 2, 3, 4]` +- C: `{1, 1, 2, 3, 4}` +- D: `{1, 2, 3, 4}` + +
答案 +

+ +#### 答案:D + +`Set` 物件是 _唯一_ 值的集合:任何存在於 `Set` 的值均為唯一的,不會存在相同的值 (重複的值將會由後出現的覆蓋已出現的)。 + +陣列 `[1, 1, 2, 3, 4]` 中有重複的值 `1`,因此結果會是 `{1, 2, 3, 4}`。 + +

+
+ +--- + +###### 57. 將會輸出什麽內容? + +```javascript +// counter.js +let counter = 10; +export default counter; +``` + +```javascript +// index.js +import myCounter from './counter'; + +myCounter += 1; + +console.log(myCounter); +``` + +- A: `10` +- B: `11` +- C: `Error` +- D: `NaN` + +
答案 +

+ +#### 答案:C + +被引用 (imported) 的模組 (module) 是 _唯讀_ 的:您無法修改被引用模組中項目,只有輸出 (export) 該項目的模組可以更改它的值。 + +因此當我們嘗試增加 `myCounter` 的值時,他將拋出錯誤:`myCounter` is read-only and cannot be modified。 + +

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

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

+
+ +--- + +###### 59. 將會輸出什麽內容? + +```javascript +const numbers = [1, 2, 3, 4, 5]; +const [y] = numbers; + +console.log(y); +``` + +- A: `[[1, 2, 3, 4, 5]]` +- B: `[1, 2, 3, 4, 5]` +- C: `1` +- D: `[1]` + +
答案 +

+ +#### 答案:C + +我們可以通過解構 (destructuring) 從陣列或物件的屬性中獲得值。例如: + +```javascript +[a, b] = [1, 2]; +``` + + + +a 的值現在為 `1` 且 b 的值現在為`2`。我們針對此問題所做的動作為: + +```javascript +[y] = [1, 2, 3, 4, 5]; +``` + + + +這代表著 `y` 的值等同於陣列中第一個元素的值,即為 `1`。因此我們執行 `console.log(y)` 時, `1` 將被輸出。 + +

+
+ +--- + +###### 60. 將會輸出什麽內容? + +```javascript +const user = { name: 'Lydia', age: 21 }; +const admin = { admin: true, ...user }; + +console.log(admin); +``` + +- A: `{ admin: true, user: { name: "Lydia", age: 21 } }` +- B: `{ admin: true, name: "Lydia", age: 21 }` +- C: `{ admin: true, user: ["Lydia", 21] }` +- D: `{ admin: true }` + +
答案 +

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

+
+ +--- + +###### 61. 將會輸出什麽內容? + +```javascript +const person = { name: 'Lydia' }; + +Object.defineProperty(person, 'age', { value: 21 }); + +console.log(person); +console.log(Object.keys(person)); +``` + +- A: `{ name: "Lydia", age: 21 }`, `["name", "age"]` +- B: `{ name: "Lydia", age: 21 }`, `["name"]` +- C: `{ name: "Lydia"}`, `["name", "age"]` +- D: `{ name: "Lydia"}`, `["age"]` + +
答案 +

+ +#### 答案:B + +透過 `defineProperty`,我們可以對物件增加新的屬性或是修改已經存在的屬性。當我們使用 `defineProperty` 增加物件的屬性時,它們被預設為 _不可 enumerable_。 + `Object.keys` 方法僅回傳物件中所有 _可 enumerable_ 的屬性名稱,這個案例中只有 `"name"`。 + +預設下,使用 `defineProperty `方法增加的屬性是不可變的。但您可以覆蓋這個行為透過 `writable`,`configurable` 及 `enumerable` 屬性。 +於是,`defineProperty` 方法可以使您對要增加到物件的屬性進行更多的控制。 + +

+
+ +--- + +###### 62. 將會輸出什麽內容? + +```javascript +const settings = { + username: 'lydiahallie', + level: 19, + health: 90, +}; + +const data = JSON.stringify(settings, ['level', 'health']); +console.log(data); +``` + +- A: `"{"level":19, "health":90}"` +- B: `"{"username": "lydiahallie"}"` +- C: `"["level", "health"]"` +- D: `"{"username": "lydiahallie", "level":19, "health":90}"` + +
答案 +

+ +#### 答案:A + +`JSON.stringify` 的第二個參數是 _替換者 (replacer)_,替換者可以是函式,也可以是陣列,並允許您控制值要如何獲怎麼串化 (stringified)。 + +如果替換者是 _陣列_,僅將陣列中包含的屬性名稱加到 JSON 字串中。 +此案例中,僅有 `"level"` and `"health"` 被包含,`"username"` 沒有被包含在內,因此 `data` 的值將為 `"{"level":19, "health":90}"`。 + +如果替換者是 _函式_,在要字串化的每個物件屬性上將會呼叫此函式。從此函式回傳的值將是加到 JSON 字串中的屬性的值。如果值為 `undefined`,則此屬性從 JSON 字串中排除。 + +

+
+ +--- + +###### 63. 將會輸出什麽內容? + +```javascript +let num = 10; + +const increaseNumber = () => num++; +const increasePassedNumber = number => number++; + +const num1 = increaseNumber(); +const num2 = increasePassedNumber(num1); + +console.log(num1); +console.log(num2); +``` + +- A: `10`, `10` +- B: `10`, `11` +- C: `11`, `11` +- D: `11`, `12` + +
答案 +

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

+
+ +--- + +###### 64. 將會輸出什麽內容? + +```javascript +const value = { number: 10 }; + +const multiply = (x = { ...value }) => { + console.log((x.number *= 2)); +}; + +multiply(); +multiply(); +multiply(value); +multiply(value); +``` + +- A: `20`, `40`, `80`, `160` +- B: `20`, `40`, `20`, `40` +- C: `20`, `20`, `20`, `40` +- D: `NaN`, `NaN`, `20`, `40` + +
答案 +

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

+
+ +--- + +###### 65. 將會輸出什麽內容? + +```javascript +[1, 2, 3, 4].reduce((x, y) => console.log(x, y)); +``` + +- A: `1` `2` and `3` `3` and `6` `4` +- B: `1` `2` and `2` `3` and `3` `4` +- C: `1` `undefined` and `2` `undefined` and `3` `undefined` and `4` `undefined` +- D: `1` `2` and `undefined` `3` and `undefined` `4` + +
答案 +

+ +#### 答案:D + +`reduce` 方法接收的第一個參數是 _累加器 (accumulator)_,在這種情況下是 `x`。第二個參數是 _current value_ `y`。使用 `reduce` 方法,我們對陣列中的每個元素執行一個 callback 函式,並在最終回一個值。 + +在此示例中,我們不回傳任何值,僅記錄了累加器的值和當前值。 + +累加器的值等於 callback 函式先前回傳的值。如果沒有 `initialValue` 參數傳遞給 `reduce` 方法,則累加器的初始值將會等於第一個元素。 + +在第一個呼叫中,累加器(`x`)為`1`,當前值(`y`)為`2`。我們不從 callback 函式回傳,而是輸出累加器和當前值:`1` 和 `2`。 + +如果您不從 callback 函式回傳值,則它將回傳 `undefined`。在下一次呼叫時,累加器為 `undefined`,當前值為 `3`。於是 `undefined` 和 `3` 被輸出。 + +在第四次呼叫中,我們再次不從 callback 函式回傳。累加器再次為 `undefined`,當前值為 `4`。於是 `undefined` 和 `4` 被輸出。 + +

+
+ +--- + +###### 66. 使用哪個建構式可以成功繼承 Dog 類別? + +```javascript +class Dog { + constructor(name) { + this.name = name; + } +}; + +class Labrador extends Dog { + // 1 + constructor(name, size) { + this.size = size; + } + // 2 + constructor(name, size) { + super(name); + this.size = size; + } + // 3 + constructor(size) { + super(name); + this.size = size; + } + // 4 + constructor(name, size) { + this.name = name; + this.size = size; + } + +}; +``` + +- A: 1 +- B: 2 +- C: 3 +- D: 4 + +
答案 +

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

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

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

+
+ +--- +###### 68. 將會輸出什麽內容? + +```javascript +console.log(Number(2) === Number(2)); +console.log(Boolean(false) === Boolean(false)); +console.log(Symbol('foo') === Symbol('foo')); +``` + +- A: `true`, `true`, `false` +- B: `false`, `true`, `false` +- C: `true`, `false`, `true` +- D: `true`, `true`, `true` + +
答案 +

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

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

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

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

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

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

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

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

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

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

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

+
+ +--- + +###### 74. 將會輸出什麽內容? + +```javascript +function addToList(item, list) { + return list.push(item); +} + +const result = addToList('apple', ['banana']); +console.log(result); +``` + +- A: `['apple', 'banana']` +- B: `2` +- C: `true` +- D: `undefined` + +
答案 +

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

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

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

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

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

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

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

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

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

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

+
+ +--- +###### 79. 將會輸出什麽內容? + +```javascript +const myLifeSummedUp = ["☕", "💻", "🍷", "🍫"] + +for (let item in myLifeSummedUp) { + console.log(item) +} + +for (let item of myLifeSummedUp) { + console.log(item) +} +``` + +- A: `0` `1` `2` `3` and `"☕"` ` "💻"` `"🍷"` `"🍫"` +- B: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `"☕"` ` "💻"` `"🍷"` `"🍫"` +- C: `"☕"` ` "💻"` `"🍷"` `"🍫"` and `0` `1` `2` `3` +- D: `0` `1` `2` `3` and `{0: "☕", 1: "💻", 2: "🍷", 3: "🍫"}` + +
答案 +

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

+
+ +--- + +###### 80. 將會輸出什麽內容? + +```javascript +const list = [1 + 2, 1 * 2, 1 / 2] +console.log(list) +``` + +- A: `["1 + 2", "1 * 2", "1 / 2"]` +- B: `["12", 2, 0.5]` +- C: `[3, 2, 0.5]` +- D: `[1, 1, 1]` + +
答案 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+
+ +--- +###### 90. 將會輸出什麽內容? + +```javascript +class Person { + constructor(name) { + this.name = name + } +} + +const member = new Person("John") +console.log(typeof member) +``` + +- A: `"class"` +- B: `"function"` +- C: `"object"` +- D: `"string"` + +
答案 +

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+