You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/01-getting-started/1-intro/article.md
+5Lines changed: 5 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -67,8 +67,13 @@ Exemplos de tais restrições incluem:
67
67
68
68
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>`.
69
69
70
+
<<<<<<< HEAD
70
71
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).
71
72
- 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
72
77
73
78
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.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/07-optional-chaining/article.md
+45-15Lines changed: 45 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,51 +9,81 @@ The optional chaining `?.` is a safe way to access nested object properties, eve
9
9
10
10
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.
11
11
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.
13
13
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:
15
15
16
16
```js run
17
-
let user = {}; //the user without "address" property
17
+
let user = {}; //a user without "address" property
18
18
19
19
alert(user.address.street); // Error!
20
20
```
21
21
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").
23
23
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:
25
25
26
26
```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
29
29
```
30
30
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.
32
32
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:
...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`:
Please note: the `?.` syntax makes optional the value before it, but not any further.
67
97
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`.
69
99
70
100
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.
71
101
72
102
```warn header="Don't overuse the optional chaining"
73
103
We should use `?.` only where it's ok that something doesn't exist.
74
104
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`.
76
106
77
107
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.
78
108
```
@@ -84,7 +114,7 @@ If there's no variable `user` at all, then `user?.anything` triggers an error:
84
114
// ReferenceError: user is not defined
85
115
user?.address;
86
116
```
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.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/05-array-methods/2-filter-range/task.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ importance: 4
4
4
5
5
# Filter range
6
6
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.
8
8
9
9
The function should not modify the array. It should return the new array.
Copy file name to clipboardExpand all lines: 2-ui/1-document/05-basic-dom-node-properties/article.md
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -424,23 +424,23 @@ Compare the two:
424
424
<div id="elem2"></div>
425
425
426
426
<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>");
428
428
429
429
elem1.innerHTML = name;
430
430
elem2.textContent = name;
431
431
</script>
432
432
```
433
433
434
434
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>`.
436
436
437
437
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.
438
438
439
439
## The "hidden" property
440
440
441
441
The "hidden" attribute and the DOM property specifies whether the element is visible or not.
442
442
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:
Copy file name to clipboardExpand all lines: 2-ui/4-forms-controls/1-form-elements/article.md
+3-1Lines changed: 3 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -215,7 +215,9 @@ Here is an example:
215
215
</script>
216
216
```
217
217
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.
219
221
220
222
We can get their collection as `select.options`, for instance:
Copy file name to clipboardExpand all lines: 9-regular-expressions/16-regexp-sticky/article.md
+34-23Lines changed: 34 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,36 +3,37 @@
3
3
4
4
The flag `pattern:y` allows to perform the search at the given position in the source string.
5
5
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.
7
7
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.
11
9
12
10
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.
13
11
14
12
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`.
15
13
16
14
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.
17
15
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?**
19
20
20
-
To search from the given position, we can use method `regexp.exec(str)`.
21
+
Let's try using method `regexp.exec(str)`.
21
22
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)`.
23
24
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.
25
26
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.
27
28
28
29
So, successive calls to `regexp.exec(str)` return matches one after another.
29
30
30
-
An example (with flag `pattern:g`):
31
+
Here's an example of such calls:
31
32
32
33
```js run
33
-
let str ='let varName';
34
-
34
+
let str ='let varName'; // Let's find all words in this string
@@ -48,8 +49,6 @@ alert(word3); // null (no more matches)
48
49
alert(regexp.lastIndex); // 0 (resets at search end)
49
50
```
50
51
51
-
Every match is returned as an array with groups and additional properties.
52
-
53
52
We can get all matches in the loop:
54
53
55
54
```js run
@@ -65,11 +64,13 @@ while (result = regexp.exec(str)) {
65
64
}
66
65
```
67
66
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.
69
68
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.
71
70
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:
73
74
74
75
```js run
75
76
let str ='let varName = "value"';
@@ -84,27 +85,35 @@ let word = regexp.exec(str);
84
85
alert(word); // varName
85
86
```
86
87
88
+
Hooray! Problem solved!
89
+
87
90
We performed a search of `pattern:\w+`, starting from position `regexp.lastIndex = 4`.
88
91
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:
90
97
91
98
```js run
92
99
let str ='let varName = "value"';
93
100
94
101
let regexp =/\w+/g;
95
102
96
103
*!*
104
+
// start the search from position 3
97
105
regexp.lastIndex=3;
98
106
*/!*
99
107
100
-
let word =regexp.exec(str);
108
+
let word =regexp.exec(str);
109
+
// found the match at position 4
101
110
alert(word[0]); // varName
102
111
alert(word.index); // 4
103
112
```
104
113
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.
106
115
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.**
108
117
109
118
Here's the same search with flag `pattern:y`:
110
119
@@ -122,6 +131,8 @@ alert( regexp.exec(str) ); // varName (word at position 4)
122
131
123
132
As we can see, regexp `pattern:/\w+/y` doesn't match at position `3` (unlike the flag `pattern:g`), but matches at position `4`.
124
133
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.
126
137
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