Skip to content

Commit f954b57

Browse files
committed
merging all conflicts
2 parents 3bc567d + d6e8864 commit f954b57

File tree

6 files changed

+91
-43
lines changed

6 files changed

+91
-43
lines changed

1-js/01-getting-started/1-intro/article.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,13 @@ Exemplos de tais restrições incluem:
6767

6868
Os navegadores modernos permitem que ele trabalhe com arquivos, mas o acesso é limitado e fornecido apenas se o usuário executar determinadas ações, como "dropping" de um arquivo em uma janela do navegador ou selecioná-lo por meio de uma tag `<input>`.
6969

70+
<<<<<<< HEAD
7071
Existem maneiras de interagir com a câmera / microfone e outros dispositivos, mas eles exigem permissão explícita do usuário. Assim, uma página habilitada para JavaScript pode não habilmente habilitar uma câmera web, observar os arredores e enviar as informações para a [NSA](https://pt.wikipedia.org/wiki/Ag%C3%AAncia_de_Seguran%C3%A7a_Nacional).
7172
- Diferentes abas/janelas geralmente não se conhecem mutuamente. Às vezes sim, por exemplo, quando uma janela usa JavaScript para abrir a outra. Mas mesmo neste caso, JavaScript de uma página pode não acessar a outra se eles vierem de sites diferentes (de um domínio, protocolo ou porta diferente).
73+
=======
74+
There are ways to interact with camera/microphone and other devices, but they require a user's explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the [NSA](https://en.wikipedia.org/wiki/National_Security_Agency).
75+
- Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other if they come from different sites (from a different domain, protocol or port).
76+
>>>>>>> d6e88647b42992f204f57401160ebae92b358c0d
7277
7378
Isso é chamado de "Política de mesma origem ". Para contornar isso, *ambas as páginas* devem conter um código JavaScript especial que lida com a troca de dados.
7479

1-js/04-object-basics/07-optional-chaining/article.md

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,51 +9,81 @@ The optional chaining `?.` is a safe way to access nested object properties, eve
99

1010
If you've just started to read the tutorial and learn JavaScript, maybe the problem hasn't touched you yet, but it's quite common.
1111

12-
As an example, let's consider objects for user data. Most of our users have addresses in `user.address` property, with the street `user.address.street`, but some did not provide them.
12+
As an example, consider objects for user data. Most of our users have addresses in `user.address` property, with the street `user.address.street`, but some did not provide them.
1313

14-
In such case, when we attempt to get `user.address.street`, we'll get an error:
14+
In such case, when we attempt to get `user.address.street`, we may get an error:
1515

1616
```js run
17-
let user = {}; // the user without "address" property
17+
let user = {}; // a user without "address" property
1818

1919
alert(user.address.street); // Error!
2020
```
2121

22-
That's the expected result, JavaScript works like this, but many practical cases we'd prefer to get `undefined` instead of an error (meaning "no street").
22+
That's the expected result, JavaScript works like this. As `user.address` is `undefined`, the attempt to get `user.address.street` fails with an error. Although, in many practical cases we'd prefer to get `undefined` instead of an error here (meaning "no street").
2323

24-
...And another example. In the web development, we may need to get an information about an element on the page, that sometimes doesn't exist:
24+
...And another example. In the web development, we may need the information about an element on the page. The element is returned by `document.querySelector('.elem')`, and the catch is again - that it sometimes doesn't exist:
2525

2626
```js run
27-
// Error if the result of querySelector(...) is null
28-
let html = document.querySelector('.my-element').innerHTML;
27+
// the result of the call document.querySelector('.elem') may be an object or null
28+
let html = document.querySelector('.elem').innerHTML; // error if it's null
2929
```
3030

31-
Before `?.` appeared in the language, the `&&` operator was used to work around that.
31+
Once again, we may want to avoid the error in such case.
3232

33-
For example:
33+
How can we do this?
34+
35+
The obvious solution would be to check the value using `if` or the conditional operator `?`, before accessing it, like this:
36+
37+
```js
38+
let user = {};
39+
40+
alert(user.address ? user.address.street : undefined);
41+
```
42+
43+
...But that's quite inelegant. As you can see, the `user.address` is duplicated in the code. For more deeply nested properties, that becomes a problem.
44+
45+
E.g. let's try getting `user.address.street.name`.
46+
47+
We need to check both `user.address` and `user.address.street`:
48+
49+
```js
50+
let user = {}; // user has no address
51+
52+
alert(user.address ? user.address.street ? user.address.street.name : null : null);
53+
```
54+
55+
That looks awful.
56+
57+
Before the optional chaining `?.` was added to the language, people used the `&&` operator for such cases:
3458

3559
```js run
3660
let user = {}; // user has no address
3761

38-
alert( user && user.address && user.address.street ); // undefined (no error)
62+
alert( user.address && user.address.street && user.address.street.name ); // undefined (no error)
3963
```
4064

41-
AND'ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but is cumbersome to write.
65+
AND'ing the whole path to the property ensures that all components exist (if not, the evaluation stops), but also isn't ideal.
66+
67+
As you can see, the property names are still duplicated in the code. E.g. in the code above, `user.address` appears three times.
68+
69+
And now, finally, the optional chaining comes to the rescue!
4270

4371
## Optional chaining
4472

4573
The optional chaining `?.` stops the evaluation and returns `undefined` if the part before `?.` is `undefined` or `null`.
4674

4775
**Further in this article, for brevity, we'll be saying that something "exists" if it's not `null` and not `undefined`.**
4876

49-
Here's the safe way to access `user.address.street`:
77+
Here's the safe way to access `user.address.street` using `?.`:
5078

5179
```js run
5280
let user = {}; // user has no address
5381

5482
alert( user?.address?.street ); // undefined (no error)
5583
```
5684
85+
The code is short and clean, there's no duplication at all.
86+
5787
Reading the address with `user?.address` works even if `user` object doesn't exist:
5888
5989
```js run
@@ -65,14 +95,14 @@ alert( user?.address.street ); // undefined
6595
6696
Please note: the `?.` syntax makes optional the value before it, but not any further.
6797
68-
In the example above, `user?.` allows only `user` to be `null/undefined`.
98+
In the example above, `user?.address.street` allows only `user` to be `null/undefined`.
6999
70100
On the other hand, if `user` does exist, then it must have `user.address` property, otherwise `user?.address.street` gives an error at the second dot.
71101
72102
```warn header="Don't overuse the optional chaining"
73103
We should use `?.` only where it's ok that something doesn't exist.
74104

75-
For example, if according to our coding logic `user` object must be there, but `address` is optional, then `user.address?.street` would be better.
105+
For example, if according to our coding logic `user` object must exist, but `address` is optional, then we should write `user.address?.street`, but not `user?.address?.street`.
76106

77107
So, if `user` happens to be undefined due to a mistake, we'll see a programming error about it and fix it. Otherwise, coding errors can be silenced where not appropriate, and become more difficult to debug.
78108
```
@@ -84,7 +114,7 @@ If there's no variable `user` at all, then `user?.anything` triggers an error:
84114
// ReferenceError: user is not defined
85115
user?.address;
86116
```
87-
There must be a declaration (e.g. `let/const/var user`). The optional chaining works only for declared variables.
117+
The variable must be declared (e.g. `let/const/var user` or as a function parameter). The optional chaining works only for declared variables.
88118
````
89119

90120
## Short-circuiting

1-js/05-data-types/05-array-methods/2-filter-range/task.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ importance: 4
44

55
# Filter range
66

7-
Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them.
7+
Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements with values higher or equal to `a` and lower or equal to `b` and return a result as an array.
88

99
The function should not modify the array. It should return the new array.
1010

2-ui/1-document/05-basic-dom-node-properties/article.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -424,23 +424,23 @@ Compare the two:
424424
<div id="elem2"></div>
425425
426426
<script>
427-
let name = prompt("What's your name?", "<b>Winnie-the-pooh!</b>");
427+
let name = prompt("What's your name?", "<b>Winnie-the-Pooh!</b>");
428428
429429
elem1.innerHTML = name;
430430
elem2.textContent = name;
431431
</script>
432432
```
433433
434434
1. The first `<div>` gets the name "as HTML": all tags become tags, so we see the bold name.
435-
2. The second `<div>` gets the name "as text", so we literally see `<b>Winnie-the-pooh!</b>`.
435+
2. The second `<div>` gets the name "as text", so we literally see `<b>Winnie-the-Pooh!</b>`.
436436
437437
In most cases, we expect the text from a user, and want to treat it as text. We don't want unexpected HTML in our site. An assignment to `textContent` does exactly that.
438438
439439
## The "hidden" property
440440
441441
The "hidden" attribute and the DOM property specifies whether the element is visible or not.
442442
443-
We can use it in HTML or assign using JavaScript, like this:
443+
We can use it in HTML or assign it using JavaScript, like this:
444444
445445
```html run height="80"
446446
<div>Both divs below are hidden</div>

2-ui/4-forms-controls/1-form-elements/article.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,9 @@ Here is an example:
215215
</script>
216216
```
217217
218-
Unlike most other controls, `<select>` allows to select multiple options at once if it has `multiple` attribute. That's feature is rarely used. In that case we need to use the first way: add/remove the `selected` property from `<option>` subelements.
218+
Unlike most other controls, `<select>` allows to select multiple options at once if it has `multiple` attribute. Although such functionality is available, it is rarely used.
219+
220+
In cases that you have to, then use the first way: add/remove the `selected` property from `<option>` subelements.
219221
220222
We can get their collection as `select.options`, for instance:
221223

9-regular-expressions/16-regexp-sticky/article.md

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,37 @@
33

44
The flag `pattern:y` allows to perform the search at the given position in the source string.
55

6-
To grasp the use case of `pattern:y` flag, and see how great it is, let's explore a practical use case.
6+
To grasp the use case of `pattern:y` flag, and better understand the ways of regexps, let's explore a practical example.
77

8-
One of common tasks for regexps is "lexical analysis": we get a text, e.g. in a programming language, and analyze it for structural elements.
9-
10-
For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.
8+
One of common tasks for regexps is "lexical analysis": we get a text, e.g. in a programming language, and need to find its structural elements. For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.
119

1210
Writing lexical analyzers is a special area, with its own tools and algorithms, so we don't go deep in there, but there's a common task: to read something at the given position.
1311

1412
E.g. we have a code string `subject:let varName = "value"`, and we need to read the variable name from it, that starts at position `4`.
1513

1614
We'll look for variable name using regexp `pattern:\w+`. Actually, JavaScript variable names need a bit more complex regexp for accurate matching, but here it doesn't matter.
1715

18-
A call to `str.match(/\w+/)` will find only the first word in the line. Or all words with the flag `pattern:g`. But we need only one word at position `4`.
16+
- A call to `str.match(/\w+/)` will find only the first word in the line (`var`). That's not it.
17+
- We can add the flag `pattern:g`. But then the call `str.match(/\w+/g)` will look for all words in the text, while we need one word at position `4`. Again, not what we need.
18+
19+
**So, how to search for a regexp exactly at the given position?**
1920

20-
To search from the given position, we can use method `regexp.exec(str)`.
21+
Let's try using method `regexp.exec(str)`.
2122

22-
If the `regexp` doesn't have flags `pattern:g` or `pattern:y`, then this method looks for the first match in the string `str`, exactly like `str.match(regexp)`. Such simple no-flags case doesn't interest us here.
23+
For a `regexp` without flags `pattern:g` and `pattern:y`, this method looks only for the first match, it works exactly like `str.match(regexp)`.
2324

24-
If there's flag `pattern:g`, then it performs the search in the string `str`, starting from position stored in its `regexp.lastIndex` property. And, if it finds a match, then sets `regexp.lastIndex` to the index immediately after the match.
25+
...But if there's flag `pattern:g`, then it performs the search in `str`, starting from position stored in the `regexp.lastIndex` property. And, if it finds a match, then sets `regexp.lastIndex` to the index immediately after the match.
2526

26-
When a regexp is created, its `lastIndex` is `0`.
27+
In other words, `regexp.lastIndex` serves as a starting point for the search, that each `regexp.exec(str)` call resets to the new value ("after the last match"). That's only if there's `pattern:g` flag, of course.
2728

2829
So, successive calls to `regexp.exec(str)` return matches one after another.
2930

30-
An example (with flag `pattern:g`):
31+
Here's an example of such calls:
3132

3233
```js run
33-
let str = 'let varName';
34-
34+
let str = 'let varName'; // Let's find all words in this string
3535
let regexp = /\w+/g;
36+
3637
alert(regexp.lastIndex); // 0 (initially lastIndex=0)
3738

3839
let word1 = regexp.exec(str);
@@ -48,8 +49,6 @@ alert(word3); // null (no more matches)
4849
alert(regexp.lastIndex); // 0 (resets at search end)
4950
```
5051

51-
Every match is returned as an array with groups and additional properties.
52-
5352
We can get all matches in the loop:
5453

5554
```js run
@@ -65,11 +64,13 @@ while (result = regexp.exec(str)) {
6564
}
6665
```
6766

68-
Such use of `regexp.exec` is an alternative to method `str.matchAll`.
67+
Such use of `regexp.exec` is an alternative to method `str.matchAll`, with a bit more control over the process.
6968

70-
Unlike other methods, we can set our own `lastIndex`, to start the search from the given position.
69+
Let's go back to our task.
7170

72-
For instance, let's find a word, starting from position `4`:
71+
We can manually set `lastIndex` to `4`, to start the search from the given position!
72+
73+
Like this:
7374

7475
```js run
7576
let str = 'let varName = "value"';
@@ -84,27 +85,35 @@ let word = regexp.exec(str);
8485
alert(word); // varName
8586
```
8687

88+
Hooray! Problem solved!
89+
8790
We performed a search of `pattern:\w+`, starting from position `regexp.lastIndex = 4`.
8891

89-
Please note: the search starts at position `lastIndex` and then goes further. If there's no word at position `lastIndex`, but it's somewhere after it, then it will be found:
92+
The result is correct.
93+
94+
...But wait, not so fast.
95+
96+
Please note: the `regexp.exec` call start searching at position `lastIndex` and then goes further. If there's no word at position `lastIndex`, but it's somewhere after it, then it will be found:
9097

9198
```js run
9299
let str = 'let varName = "value"';
93100

94101
let regexp = /\w+/g;
95102

96103
*!*
104+
// start the search from position 3
97105
regexp.lastIndex = 3;
98106
*/!*
99107

100-
let word = regexp.exec(str);
108+
let word = regexp.exec(str);
109+
// found the match at position 4
101110
alert(word[0]); // varName
102111
alert(word.index); // 4
103112
```
104113

105-
...So, with flag `pattern:g` property `lastIndex` sets the starting position for the search.
114+
For some tasks, including the lexical analysis, that's just wrong. We need to find a match exactly at the given position at the text, not somewhere after it. And that's what the flag `y` is for.
106115

107-
**Flag `pattern:y` makes `regexp.exec` to look exactly at position `lastIndex`, not before, not after it.**
116+
**The flag `pattern:y` makes `regexp.exec` to search exactly at position `lastIndex`, not "starting from" it.**
108117

109118
Here's the same search with flag `pattern:y`:
110119

@@ -122,6 +131,8 @@ alert( regexp.exec(str) ); // varName (word at position 4)
122131

123132
As we can see, regexp `pattern:/\w+/y` doesn't match at position `3` (unlike the flag `pattern:g`), but matches at position `4`.
124133

125-
Imagine, we have a long text, and there are no matches in it, at all. Then searching with flag `pattern:g` will go till the end of the text, and this will take significantly more time than the search with flag `pattern:y`.
134+
Not only that's what we need, there's an important performance gain when using flag `pattern:y`.
135+
136+
Imagine, we have a long text, and there are no matches in it, at all. Then a search with flag `pattern:g` will go till the end of the text and find nothing, and this will take significantly more time than the search with flag `pattern:y`, that checks only the exact position.
126137

127-
In such tasks like lexical analysis, there are usually many searches at an exact position. Using flag `pattern:y` is the key for a good performance.
138+
In tasks like lexical analysis, there are usually many searches at an exact position, to check what we have there. Using flag `pattern:y` is the key for correct implementations and a good performance.

0 commit comments

Comments
 (0)