Skip to content

Commit 0818e61

Browse files
committed
ok
1 parent b78f329 commit 0818e61

File tree

20 files changed

+251
-150
lines changed

20 files changed

+251
-150
lines changed

1-js/1-getting-started/2-editor/article.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ If you haven't considered selecting an IDE, pleae look at the following variants
1818
- Visual Studio is fine if you're a .NET developer.
1919
- Eclipse-based products, like [Aptana](http://www.aptana.com/) and Zend Studio.
2020
- [Komodo IDE](http://www.activestate.com/komodo-ide) and it's lightweight free version [Komodo Edit](http://www.activestate.com/komodo-edit).
21-
- [Netbeans](http://netbeans.org/)
21+
- [Netbeans](http://netbeans.org/).
2222

2323
All of them with the exception of Visual Studio are cross-platform.
2424

@@ -30,9 +30,9 @@ Most IDEs are paid, but have a trial period. Their cost is usually negligible co
3030

3131
They are mainly used to instantly open and edit a file.
3232

33-
The main difference between a "lightweight editor" and an "IDE" is that the latter works on a project-level, meaning it has to load a lot of data to start, and the former one opens just the files. That's much faster.
33+
The main difference between a "lightweight editor" and an "IDE" is that IDE works on a project-level, so it loads much more data on start, analyzes the project structure if needed and so on. A lightweight editor is much faster if we need only one file.
3434

35-
In practice, "lightweight" editors may have a lot of plugins including directory-level syntax analyzers and autocompleters, so there's no strict border between a lightweight editor and an IDE.
35+
In practice, lightweight editors may have a lot of plugins including directory-level syntax analyzers and autocompleters, so there's no strict border between a lightweight editor and an IDE.
3636

3737
The following options deserve your attention:
3838

@@ -43,7 +43,7 @@ The following options deserve your attention:
4343

4444
## My favorites
4545

46-
I believe one should have both an IDE for projects and a lightweight editor for quick and easy file editing.
46+
The personal preference of the author is to have both an IDE for projects and a lightweight editor for quick and easy file editing.
4747

4848
I'm using:
4949

@@ -54,7 +54,7 @@ If you don't know what to choose -- you can consider these ones.
5454

5555
## Let's not argue
5656

57-
The editors in the lists above are those that me or my friends -- good developers use for a long time and are happy with.
57+
The editors in the lists above are those that me or my friends -- good developers are using for a long time and are happy with.
5858

5959
There are other great editors in our big world, please choose the one you like the most.
6060

1-js/1-getting-started/3-devtools/article.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ To see errors and get a lot of other useful information about scripts, browsers
1010

1111
**Most often developers lean towards Chrome or Firefox for the development.**
1212

13-
Other browsers also provide developer tools, but are usually in a "catching-up" position, compared to Chrome/Firefox which are the best.
13+
Other browsers also provide developer tools, but are usually in a "catching-up" position, compared to Chrome/Firefox which are the best.
1414

15-
If there is an error in the certain browser only, then we can always switch to it's developer tools for the concrete problem.
15+
Sometimes, it may be required to switch to another browser, if a problem is browser-specific, but that's rare.
1616

17-
Developer tools are really powerful, there are many features. On this stage let's just look how to open them, look at errors and run JavaScript commands.
17+
Developer tools are really powerful, there are many features. Here, for the start, we'll learn how to open them, look at errors and run JavaScript commands.
1818

1919
[cut]
2020

1-js/2-first-steps/01-hello-world/article.md

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
# Hello, world!
22

3-
About 98% of the tutorial is core Javascript, that is platform-independant. So you'll be able to learn how to use Node.JS and other things based on that knowledge.
3+
The tutorial that you're reading is about core Javascript, that is platform-independant. So you'll be able to learn how to use Node.JS and other things based on that knowledge.
44

5-
But we need something like a "base environment" to run our scripts, and browser is probably a good choice.
5+
But we need a working environment to run our scripts, and browser is probably a good choice. Also we'll use few browser-specific commands like `alert`, but will keep their amount to the minimum.
66

7-
So we'll start with attaching a script to the webpage. For other environments like Node.JS there are other ways to run it.
7+
So we'll start with attaching a script to the webpage. For other environments like Node.JS there are other, probably even easier ways to run it.
88

99
[cut]
1010

@@ -134,4 +134,3 @@ The example above can be split into two scripts to work:
134134
135135
136136
There is much more about browser scripts and their interaction with the web-page. But let's keep in mind that this part of the tutorial is devoted to Javascript language. So we shouldn't distract ourselves from it. We'll be using a browser as a way to run Javascript, very convenient for online reading, but yet one of many.
137-

1-js/2-first-steps/04-variables/article.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ let имя = '...';
193193
let 我 = '...';
194194
```
195195
196-
Technically, there is no error here, such names are allowed, but there is an international tradition to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People coming with another language background may need to read it some time.
196+
Technically, there is no error here, such names are allowed, but there is an international tradition to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
197197
````
198198

199199
````warn header="Reserved names"

1-js/2-first-steps/05-types/article.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
There are 7 data types in JavaScript.
44

5-
Here we will get the common understanding of them. In the next chapters we'll talk about each type in detail.
5+
In this chapter we'll get the common understanding of them. In further chapters we'll talk about each type in detail.
66

77
[cut]
88

1-js/2-first-steps/16-javascript-specials/article.md

Lines changed: 95 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,193 +1,172 @@
1-
# TODO: Всё вместе: особенности JavaScript
1+
# JavaScript specials: all together
22

3-
В этой главе приводятся основные особенности JavaScript, на уровне базовых конструкций, типов, синтаксиса.
3+
This chapter aims to list features of JavaScript that we've learned, paying special attention to unobvious moments.
44

5-
Она будет особенно полезна, если ранее вы программировали на другом языке, ну или как повторение важных моментов раздела.
6-
7-
Всё очень компактно, со ссылками на развёрнутые описания.
5+
That's especially useful if you came from another language or, just as a recap.
86

97
[cut]
108

11-
## Структура кода
12-
13-
Операторы разделяются точкой с запятой:
14-
15-
```js run no-beautify
16-
alert('Привет'); alert('Мир');
17-
```
9+
## Code structure
1810

19-
Как правило, перевод строки тоже подразумевает точку с запятой. Так тоже будет работать:
11+
Statements are delimited with a semicolon:
2012

2113
```js run no-beautify
22-
alert('Привет')
23-
alert('Мир')
14+
alert('Hello'); alert('World');
2415
```
2516

26-
...Однако, иногда JavaScript не вставляет точку с запятой. Например:
17+
Usually, a line-break is also treated as a delimiter, so that would also work:
2718

2819
```js run no-beautify
29-
let a = 2
30-
+3
31-
32-
alert(a); // 5
20+
alert('Hello')
21+
alert('World')
3322
```
3423

35-
Бывают случаи, когда это ведёт к ошибкам, которые достаточно трудно найти и исправить, например:
24+
That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance:
3625

3726
```js run
38-
alert("После этого сообщения будет ошибка")
27+
alert("There will be an error after this message")
3928

4029
[1, 2].forEach(alert)
4130
```
4231

43-
Детали того, как работает код выше (массивы `[...]` и `forEach`) мы скоро изучим, здесь важно то, что при установке точки с запятой после `alert` он будет работать корректно.
32+
Most codestyle guides agree that we should put a semicolon after each statement.
4433

45-
**Поэтому в JavaScript рекомендуется точки с запятой ставить. Сейчас это, фактически, общепринятый стандарт.**
34+
Semicolons are not required after code blocks `{...}` and syntax constructs with them:
4635

47-
Поддерживаются однострочные комментарии `// ...` и многострочные `/* ... */`:
36+
```js
37+
function f() {
38+
// no semicolon after function declaration
39+
}
4840

49-
Подробнее: <info:structure>.
41+
for(;;) { /* no semicolon */ }
42+
```
5043

51-
## Переменные и типы
44+
...But even if we can put a semicolon there, that's not an error, extra semicolons do nothing.
5245

53-
- Объявляются директивой `let`. Могут хранить любое значение:
46+
More in: <info:structure>.
5447

55-
```js
56-
let x = 5;
57-
x = "Петя";
58-
```
59-
- Есть 5 "примитивных" типов и объекты:
60-
61-
```js no-beautify
62-
x = 1; // число
63-
x = "Тест"; // строка, кавычки могут быть одинарные или двойные
64-
x = true; // булево значение true/false
65-
x = null; // спец. значение (само себе тип)
66-
x = undefined; // спец. значение (само себе тип)
67-
```
48+
## Strict mode
6849

69-
Также есть специальные числовые значения `Infinity` (бесконечность) и `NaN`.
50+
To fully enable all features of modern JavaScript, we should start scripts with `"use strict"`.
7051

71-
Значение `NaN` обозначает ошибку и является результатом числовой операции, если она некорректна.
72-
- **Значение `null` не является "ссылкой на нулевой адрес/объект" или чем-то подобным. Это просто специальное значение.**
52+
```js
53+
'use strict';
7354

74-
Оно присваивается, если мы хотим указать, что значение переменной неизвестно.
55+
...
56+
```
7557

76-
Например:
58+
The directive must be at the top of a script or at the beginning of a function.
7759

78-
```js
79-
let age = null; // возраст неизвестен
80-
```
81-
- **Значение `undefined` означает "переменная не присвоена".**
60+
Without `"use strict"`, everything still works, but some features behave in old-fasion, "compatible" way. We'd generally prefer the modern behavior.
8261

83-
Например:
62+
Later we'll get acquanted with advanced features of the language that enable strict mode implicitly.
8463

85-
```js
86-
let x;
87-
alert( x ); // undefined
88-
```
64+
More in: <info:strict-mode>.
8965

90-
Можно присвоить его и явным образом: `x = undefined`, но так делать не рекомендуется.
66+
## Variables
9167

92-
Про объекты мы поговорим в главе <info:object>, они в JavaScript сильно отличаются от большинства других языков.
93-
- В имени переменной могут быть использованы любые буквы или цифры, но цифра не может быть первой. Символы доллар `$` и подчёркивание `_` допускаются наравне с буквами.
68+
Can be declared using:
9469

95-
Подробнее: <info:variables>, <info:types-intro>.
70+
- `let` (block-level visibility)
71+
- `const` (can't be changed)
72+
- `var` (old-style, will see later)
9673

97-
## Строгий режим
74+
A variable name can include:
75+
- Letters and digits, but the first character may not be a digit.
76+
- Characters `$` and `_` are normal, on par with letters.
77+
- Non-latin alphabets and hieroglyphs are also allowed, but commonly not used.
9878

99-
Для того, чтобы интерпретатор работал в режиме максимального соответствия современному стандарту, нужно начинать скрипт директивой `'use strict';`
79+
Variables are dynamically typed -- they can store any value:
10080

10181
```js
102-
'use strict';
103-
104-
...
82+
let x = 5;
83+
x = "John";
10584
```
10685

107-
Эта директива может также указываться в начале функций. При этом функция будет выполняться в режиме соответствия, а на внешний код такая директива не повлияет.
86+
There are 7 data types:
10887

109-
Одно из важных изменений в современном стандарте -- все переменные нужно объявлять через `let`. Есть и другие, которые мы изучим позже, вместе с соответствующими возможностями языка.
88+
- `number` for both floating-point and integer numbers,
89+
- `string` for strings,
90+
- `boolean` for logical values: `true/false`,
91+
- `null` -- a type with a single value `null`, meaning "empty" or "does not exist",
92+
- `undefined` -- a type with a single value `undefined`, meaning "not assigned",
93+
- `object` and `symbol` -- for complex data structures and unique identifiers, we didn't learn them yet.
11094

111-
## Взаимодействие с посетителем
95+
More in: <info:variables>, <info:types>.
11296

113-
Простейшие функции для взаимодействия с посетителем в браузере:
97+
## Interaction
11498

115-
["prompt(вопрос[, по_умолчанию])"](https://developer.mozilla.org/en/DOM/window.prompt)
116-
: Задать `вопрос` и возвратить введённую строку, либо `null`, если посетитель нажал "Отмена".
99+
We're using a browser as a working environment, so basic UI functions will be:
117100

118-
["confirm(вопрос)"](https://developer.mozilla.org/en/DOM/window.confirm)
119-
: Задать `вопрос` и предложить кнопки "Ок", "Отмена". Возвращает, соответственно, `true/false`.
101+
[`prompt(question[, default])`](mdn:api/Window/prompt)
102+
: Ask a `question`, and return either what the visitor entered or `null` if he pressed "cancel".
120103

121-
["alert(сообщение)"](https://developer.mozilla.org/en/DOM/window.alert)
122-
: Вывести сообщение на экран.
104+
[`confirm(question)`](mdn:api/Window/confirm)
105+
: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`.
123106

124-
Все эти функции являются *модальными*, т.е. не позволяют посетителю взаимодействовать со страницей до ответа.
107+
[`alert(message)`](mdn:api/Window/alert)
108+
: Output a `message`.
125109

126-
Например:
110+
All these functions are *modal*, they pause the code execution and prevent the visitor from interaction with the page until he answers.
111+
112+
For instance:
127113

128114
```js run
129-
let userName = prompt("Введите имя?", "Василий");
130-
let isTeaWanted = confirm("Вы хотите чаю?");
115+
let userName = prompt("Your name?", "Alice");
116+
let isTeaWanted = confirm("Do you want some tea?");
131117

132-
alert( "Посетитель: " + userName );
133-
alert( "Чай: " + isTeaWanted );
118+
alert( "Visitor: " + userName );
119+
alert( "Tea wanted: " + isTeaWanted );
134120
```
135121

136-
Подробнее: <info:uibasic>.
122+
More in: <info:uibasic>.
137123

138-
## Особенности операторов
124+
## Operators
139125

140-
- **Для сложения строк используется оператор `+`.**
126+
JavaScript supports following operators:
141127

142-
Если хоть один аргумент -- строка, то другой тоже приводится к строке:
128+
Arithmetical
129+
: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number.
143130

144-
```js run
145-
alert( 1 + 2 ); // 3, число
146-
alert( '1' + 2 ); // '12', строка
147-
alert( 1 + '2' ); // '12', строка
148-
```
149-
- **Сравнение `===` проверяет точное равенство, включая одинаковый тип.** Это самый очевидный и надёжный способ сравнения.
131+
Binary plus `+` contatenates strings.
150132

151-
**Остальные сравнения `== < <= > >=` осуществляют числовое приведение типа:**
133+
If any of the operands is a string -- the other one is converted to string too:
152134

153135
```js run
154-
alert( 0 == false ); // true
155-
alert( true > 0 ); // true
136+
alert( '1' + 2 ); // '12', string
137+
alert( 1 + '2' ); // '12', string
156138
```
157139

158-
Исключение -- сравнение двух строк (см. далее).
140+
Assignments
141+
: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
159142

160-
**Исключение: значения `null` и `undefined` ведут себя в сравнениях не как ноль.**
161-
<ul>
162-
<li>Они равны `null == undefined` друг другу и не равны ничему ещё. В частности, не равны нулю.
163-
- В других сравнениях (кроме `===`) значение `null` преобразуется к нулю, а `undefined` -- становится `NaN` ("ошибка").
143+
Bitwise
144+
: Bitwise operators work with integers on bit-level: see the [docs](mdn:JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
164145

165-
Такое поведение может привести к неочевидным результатам, поэтому лучше всего использовать для сравнения с ними `===`. Оператор `==` тоже можно, если не хотите отличать `null` от `undefined`.
146+
Ternary
147+
: The only operator with three parameters: `cond ? resultA : result B`
166148

167-
Например, забавное следствие этих правил для `null`:
149+
Logical operators
150+
: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped.
168151

169-
```js run no-beautify
170-
alert( null > 0 ); // false, т.к. null преобразовано к 0
171-
alert( null >= 0 ); // true, т.к. null преобразовано к 0
172-
alert( null == 0 ); // false, в стандарте явно указано, что null равен лишь undefined
173-
```
152+
Comparisons
153+
: Equality check `===` immediately fails if types are different.
174154

175-
С точки зрения здравого смысла такое невозможно. Значение `null` не равно нулю и не больше, но при этом `null >= 0` возвращает `true`!
176-
</li>
177-
</ol>
155+
Other comparisons perform type conversions, usually to a number:
178156

179-
<li>**Сравнение строк -- лексикографическое, символы сравниваются по своим unicode-кодам.**
157+
```js run
158+
alert( 0 == false ); // true
159+
alert( true > 0 ); // true
160+
```
180161

181-
Поэтому получается, что строчные буквы всегда больше, чем прописные:
162+
Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else.
182163

183-
```js run
184-
alert( 'а' > 'Я' ); // true
185-
```
164+
Greater/less comparisons compare strings character-by-character, other types are converted to a number.
186165

187-
</li>
188-
</ul>
166+
Others
167+
: There are few others, like a comma operator.
189168

190-
Подробнее: <info:operators>, <info:comparison>.
169+
More in: <info:operators>, <info:comparison>.
191170

192171
## Логические операторы
193172

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Sure, it works, no problem.
2+
3+
The `const` only protects the variable itself from changing.
4+
5+
In other words, `user` stores a reference to the object. And it can't be changed. But the content of the object can.
6+
7+
```js run
8+
const user = {
9+
name: "John"
10+
};
11+
12+
*!*
13+
// works
14+
user.name = "Pete";
15+
*/!*
16+
17+
// error
18+
user = 123;
19+
```

0 commit comments

Comments
 (0)