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
+4Lines changed: 4 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -105,7 +105,11 @@ Javascript – це єдина браузерна технологія, яка
105
105
106
106
Сучасні інструменти роблять транспіляцію дуже швидкою і прозорою, дозволяючи розробникам писати код іншою мовою і автоматично конвертувати його "під капотом".
107
107
108
+
<<<<<<< HEAD
108
109
Приклади таких мов:
110
+
=======
111
+
Examples of such languages:
112
+
>>>>>>> 6bbe0b4313a7845303be835d632ef8e5bc7715cd
109
113
110
114
-[CoffeeScript](http://coffeescript.org/) це "синтаксичний цукор" поверх JavaScript. Вона вводить більш короткий синтаксис, дозволяючи нам писати більш чіткий і точний код. Зазвичай, програмісти на Ruby люблять її.
111
115
-[TypeScript](http://www.typescriptlang.org/) зосереджена на додаванні "строгої типізації даних", щоб спростити розробку і підтримку складних систем. ЇЇ розробляє Microsoft.
Останні три рядки можуть потребувати додаткового пояснення:
221
221
222
+
<<<<<<< HEAD
222
223
1.`Math` — це вбудований об'єкт, який забезпечує математичні операції.
223
224
2. Рзультатом `typeof null` є `"object"`. Це неправильно. Це офіційно визнана помилка в "typeof", що зберігається для сумісності. Звичайно, `null` не є об'єктом. Це особливе значення з власним типом. Отже, знову ж таки, це помилка в мові.
224
225
3. Результатом `typeof alert` є `"function"`, тому що `alert` — це функція мови. Ми будемо вивчати функції в наступних розділах, де ми побачимо, що в JavaScript немає спеціального типу "function". Функції належать до типу об'єкта. Але `typeof` трактує їх по-різному. Формально це неправильно, але дуже зручно на практиці.
226
+
=======
227
+
1.`Math` is a built-in object that provides mathematical operations. We will learn it in the chapter <info:number>. Here, it serves just as an example of an object.
228
+
2. The result of `typeof null` is `"object"`. That's wrong. It is an officially recognized error in `typeof`, kept for compatibility. Of course, `null` is not an object. It is a special value with a separate type of its own. So, again, this is an error in the language.
229
+
3. The result of `typeof alert` is `"function"`, because `alert` is a function. We'll study functions in the next chapters where we'll also see that there's no special "function" type in JavaScript. Functions belong to the object type. But `typeof` treats them differently, returning `"function"`. That's not quite correct, but very convenient in practice.
Якщо вираз має більше одного оператора, порядок виконання визначається їх *пріоритетом*, або, іншими словами, неявним порядком пріоритетів операторів.
132
+
=======
133
+
If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, the default priority order of operators.
134
+
>>>>>>> 6bbe0b4313a7845303be835d632ef8e5bc7715cd
131
135
132
136
Зі школи ми всі знаємо, що множення у виразі `1 + 2 * 2` повинно бути обчислене перед додаванням. Саме це і є пріоритетом. Кажуть, що множення має *вищий пріоритет*, ніж додавання.
133
137
138
+
<<<<<<< HEAD
134
139
Дужки перевизначають будь-який пріоритет, тому, якщо ми не задоволенні неявним приорітетом, ми можемо використовувати дужки, щоб змінити його. Наприклад: `(1 + 2) * 2`.
140
+
=======
141
+
Parentheses override any precedence, so if we're not satisfied with the default order, we can use them to change it. For example, write `(1 + 2) * 2`.
142
+
>>>>>>> 6bbe0b4313a7845303be835d632ef8e5bc7715cd
135
143
136
144
У JavaScript є багато операторів. Кожен оператор має відповідний номер пріоритету. Першим виконується той оператор, який має найбільший номер пріоритету. Якщо пріоритет є однаковим, порядок виконання — зліва направо.
137
145
@@ -199,9 +207,15 @@ alert( a ); // 3
199
207
alert( c ); // 0
200
208
```
201
209
210
+
<<<<<<< HEAD
202
211
У наведенному вище прикладі результат `(a = b + 1)` є значенням, яке присвоюється змінній `a` (тобто `3`). Потім воно використовується для віднімання від `3`.
203
212
204
213
Смішний код, чи не так? Ми повинні зрозуміти, як це працює, бо іноді ми бачимо подібне у сторонніх бібліотеках, але самі не повинні писати нічого подібного. Такі трюки, безумовно, не роблять код більш ясним або читабельним.
214
+
=======
215
+
In the example above, the result of expression `(a = b + 1)` is the value which was assigned to `a` (that is `3`). It is then used for further evaluations.
216
+
217
+
Funny code, isn't it? We should understand how it works, because sometimes we see it in JavaScript libraries, but shouldn't write anything like that ourselves. Such tricks definitely don't make code clearer or readable.
Зверніть увагу, що оператор кома має дуже низький пріоритет, нижчий за `=`, тому дужки є важливими в наведеному вище прикладі.
429
443
444
+
<<<<<<< HEAD
430
445
Без них: `a = 1 + 2, 3 + 4` обчислює спочатку `+`, підсумовуючи числа у `a = 3, 7`, потім оператор присвоєння `=` присвоює `a = 3`, і нарешті число після коми, `7`, не обробляється та ігнорується.
431
446
```
432
447
433
448
Чому нам потрібен оператор, що викидає все, окрім останньої частини?
449
+
=======
450
+
Without them: `a = 1 + 2, 3 + 4` evaluates `+` first, summing the numbers into `a = 3, 7`, then the assignment operator `=` assigns `a = 3`, and the rest is ignored. It's like `(a = 1 + 2), 3 + 4`.
451
+
```
452
+
453
+
Why do we need an operator that throws away everything except the last expression?
454
+
>>>>>>> 6bbe0b4313a7845303be835d632ef8e5bc7715cd
434
455
435
456
Іноді люди використовують його в більш складних конструкціях, щоб помістити кілька дій в один рядок.
436
457
@@ -443,4 +464,8 @@ for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) {
443
464
}
444
465
```
445
466
467
+
<<<<<<< HEAD
446
468
Такі трюки використовуються в багатьох фреймворках JavaScript. Саме тому ми їх згадуємо. Але, як правило, вони не покращують читабельність коду, тому ми повинні добре подумати перед їх використанням.
469
+
=======
470
+
Such tricks are used in many JavaScript frameworks. That's why we're mentioning them. But usually they don't improve code readability so we should think well before using them.
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/02-coding-style/article.md
+40-22Lines changed: 40 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,11 +2,11 @@
2
2
3
3
Our code must be as clean and easy to read as possible.
4
4
5
-
That is actually the art of programming -- to take a complex task and code it in a way that is both correct and human-readable.
5
+
That is actually the art of programming -- to take a complex task and code it in a way that is both correct and human-readable. A good code style greatly assists in that.
6
6
7
7
## Syntax
8
8
9
-
Here is a cheatsheet with some suggested rules (see below for more details):
9
+
Here is a cheat sheet with some suggested rules (see below for more details):
10
10
11
11

12
12
<!--
@@ -36,7 +36,7 @@ if (n < 0) {
36
36
37
37
Now let's discuss the rules and reasons for them in detail.
38
38
39
-
```warn header="Irony Detected"
39
+
```warn header="There are no \"you must\" rules"
40
40
Nothing is set in stone here. These are style preferences, not religious dogmas.
41
41
```
42
42
@@ -52,7 +52,7 @@ if (condition) {
52
52
}
53
53
```
54
54
55
-
A single-line constructis an important edge case. Should we use brackets at all? If yes, then where?
55
+
A single-line construct, such as `if (condition) doSomething()`, is an important edge case. Should we use braces at all?
56
56
57
57
Here are the annotated variants so you can judge their readability for yourself:
58
58
@@ -72,13 +72,31 @@ if (n < 0) {
72
72
-->
73
73

74
74
75
-
In summary:
76
-
- For very short code, one line is acceptable. For example: `if (cond) return null`.
77
-
- But a separate line for each statement in brackets is usually easier to read.
78
-
79
75
### Line Length
80
76
81
-
No one likes to read a long horizontal line of code. It's best practice to split them up and limit the length of your lines.
77
+
No one likes to read a long horizontal line of code. It's best practice to split them.
78
+
79
+
For example:
80
+
```js
81
+
// backtick quotes ` allow to split the string into multiple lines
82
+
let str =`
83
+
Ecma International's TC39 is a group of JavaScript developers,
84
+
implementers, academics, and more, collaborating with the community
85
+
to maintain and evolve the definition of JavaScript.
86
+
`;
87
+
```
88
+
89
+
And, for `if` statements:
90
+
91
+
```js
92
+
if (
93
+
id ===123&&
94
+
moonPhase ==='Waning Gibbous'&&
95
+
zodiacSign ==='Libra'
96
+
) {
97
+
letTheSorceryBegin();
98
+
}
99
+
```
82
100
83
101
The maximum line length should be agreed upon at the team-level. It's usually 80 or 120 characters.
84
102
@@ -127,15 +145,15 @@ There are two types of indents:
127
145
128
146
A semicolon should be present after each statement, even if it could possibly be skipped.
129
147
130
-
There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors.
148
+
There are languages where a semicolon is truly optional and it is rarely used. In JavaScript, though, there are cases where a line break is not interpreted as a semicolon, leaving the code vulnerable to errors.See more about that in the chapter <info:structure#semicolon>.
131
149
132
-
As you become more mature as a programmer, you may choose a no-semicolon style like [StandardJS](https://standardjs.com/). Until then, it's best to use semicolons to avoid possible pitfalls.
150
+
If you're an experienced JavaScript programmer, you may choose a no-semicolon code style like [StandardJS](https://standardjs.com/). Otherwise, it's best to use semicolons to avoid possible pitfalls. The majority of developers put semicolons.
133
151
134
152
### Nesting Levels
135
153
136
154
Try to avoid nesting code too many levels deep.
137
155
138
-
Sometimes it's a good idea to use the ["continue"](info:while-for#continue) directive in a loop to avoid extra nesting.
156
+
For example, in the loop, it's sometimes a good idea to use the ["continue"](info:while-for#continue) directive to avoid extra nesting.
139
157
140
158
For example, instead of adding a nested `if` conditional like this:
141
159
@@ -197,13 +215,13 @@ function pow(x, n) {
197
215
}
198
216
```
199
217
200
-
The second one is more readable because the "edge case" of `n < 0` is handled early on. Once the check is done we can move on to the "main" code flow without the need for additional nesting.
218
+
The second one is more readable because the "special case" of `n < 0` is handled early on. Once the check is done we can move on to the "main" code flow without the need for additional nesting.
201
219
202
220
## Function Placement
203
221
204
222
If you are writing several "helper" functions and the code that uses them, there are three ways to organize the functions.
205
223
206
-
1. Functions declared above the code that uses them:
224
+
1. Declare the functions *above* the code that uses them:
207
225
208
226
```js
209
227
// *!*function declarations*/!*
@@ -249,15 +267,15 @@ If you are writing several "helper" functions and the code that uses them, there
249
267
250
268
Most of time, the second variant is preferred.
251
269
252
-
That's because when reading code, we first want to know *what it does*. If the code goes first, then it provides that information. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do.
270
+
That's because when reading code, we first want to know *what it does*. If the code goes first, then it becomes clear from the start. Then, maybe we won't need to read the functions at all, especially if their names are descriptive of what they actually do.
253
271
254
272
## Style Guides
255
273
256
274
A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, where to put line breaks, etc. A lot of minor things.
257
275
258
276
When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it.
259
277
260
-
Of course, a team can always write their own style guide. Mostof the time though, there's no need to. There are many existing tried and true options to choose from, so adopting one of these is usually your best bet.
278
+
Of course, a team can always write their own style guide, but usually there's no need to. There are many existing guides to choose from.
261
279
262
280
Some popular choices:
263
281
@@ -267,15 +285,15 @@ Some popular choices:
267
285
- [StandardJS](https://standardjs.com/)
268
286
- (plus many more)
269
287
270
-
If you're a novice developer, start with the cheatsheet at the beginning ofthischapter. Once you've mastered that you can browse other style guides to pick up common principles and decide which one you like best.
288
+
If you're a novice developer, start with the cheat sheet at the beginning ofthischapter. Then youcan browse other style guides to pick up more ideas and decide which one you like best.
271
289
272
290
## Automated Linters
273
291
274
-
Linters are tools that can automatically check the style of your code and make suggestions for refactoring.
292
+
Linters are tools that can automatically check the style of your code and make improving suggestions.
275
293
276
-
The great thing about them is that style-checking can also find some bugs, like typos in variable or function names. Because of this feature, installing a linter is recommended even if you don't want to stick to one particular "code style".
294
+
The great thing about them is that style-checking can also find some bugs, like typos in variable or function names. Because of this feature, using a linter is recommended even if you don't want to stick to one particular "code style".
277
295
278
-
Here are the most well-known linting tools:
296
+
Here are some well-known linting tools:
279
297
280
298
- [JSLint](http://www.jslint.com/) -- one of the first linters.
281
299
- [JSHint](http://www.jshint.com/) -- more settings than JSLint.
@@ -317,8 +335,8 @@ Also certain IDEs have built-in linting, which is convenient but not as customiz
317
335
318
336
## Summary
319
337
320
-
All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code, but all of them are debatable.
338
+
All syntax rules described in this chapter (and in the style guides referenced) aim to increase the readability of your code. All of them are debatable.
321
339
322
-
When we think about writing "better" code, the questions we should ask are, "What makes the code more readable and easier to understand?" and "What can help us avoid errors?" These are the main things to keep in mind when choosing and debating code styles.
340
+
When we think about writing "better" code, the questions we should ask ourselves are: "What makes the code more readable and easier to understand?" and "What can help us avoid errors?" These are the main things to keep in mind when choosing and debating code styles.
323
341
324
342
Reading popular style guides will allow you to keep up to date with the latest ideas about code style trends and best practices.
0 commit comments