minor fixes

This commit is contained in:
Ilya Kantor 2019-07-26 23:21:49 +03:00
parent 689975093c
commit f6ff773033
24 changed files with 67 additions and 76 deletions

View file

@ -50,11 +50,11 @@ Open Preferences and go to the "Advanced" pane. There's a checkbox at the bottom
Now `key:Cmd+Opt+C` can toggle the console. Also, note that the new top menu item named "Develop" has appeared. It has many commands and options. Now `key:Cmd+Opt+C` can toggle the console. Also, note that the new top menu item named "Develop" has appeared. It has many commands and options.
## Multi-line input ```smart header="Multi-line input"
Usually, when we put a line of code into the console, and then press `key:Enter`, it executes. Usually, when we put a line of code into the console, and then press `key:Enter`, it executes.
To insert multiple lines, press `key:Shift+Enter`. To insert multiple lines, press `key:Shift+Enter`. This way one can enter long fragments of JavaScript code.
```
## Summary ## Summary

View file

@ -1,6 +1,6 @@
# Hello, world! # Hello, world!
This part of the tutorial is about core JavaScript, the language itself. Later on, you'll learn about Node.js and other platforms that use it. This part of the tutorial is about core JavaScript, the language itself.
But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`) to a minimum so that you don't spend time on them if you plan to concentrate on another environment (like Node.js). We'll focus on JavaScript in the browser in the [next part](/ui) of the tutorial. But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`) to a minimum so that you don't spend time on them if you plan to concentrate on another environment (like Node.js). We'll focus on JavaScript in the browser in the [next part](/ui) of the tutorial.
@ -46,7 +46,7 @@ The `<script>` tag contains JavaScript code which is automatically executed when
The `<script>` tag has a few attributes that are rarely used nowadays but can still be found in old code: The `<script>` tag has a few attributes that are rarely used nowadays but can still be found in old code:
The `type` attribute: <code>&lt;script <u>type</u>=...&gt;</code> The `type` attribute: <code>&lt;script <u>type</u>=...&gt;</code>
: The old HTML standard, HTML4, required a script to have a `type`. Usually it was `type="text/javascript"`. It's not required anymore. Also, the modern HTML standard, HTML5, totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic; we'll talk about modules in another part of the tutorial. : The old HTML standard, HTML4, required a script to have a `type`. Usually it was `type="text/javascript"`. It's not required anymore. Also, the modern HTML standard totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic; we'll talk about modules in another part of the tutorial.
The `language` attribute: <code>&lt;script <u>language</u>=...&gt;</code> The `language` attribute: <code>&lt;script <u>language</u>=...&gt;</code>
: This attribute was meant to show the language of the script. This attribute no longer makes sense because JavaScript is the default language. There is no need to use it. : This attribute was meant to show the language of the script. This attribute no longer makes sense because JavaScript is the default language. There is no need to use it.
@ -73,9 +73,7 @@ Script files are attached to HTML with the `src` attribute:
<script src="/path/to/script.js"></script> <script src="/path/to/script.js"></script>
``` ```
Here, `/path/to/script.js` is an absolute path to the script file (from the site root). Here, `/path/to/script.js` is an absolute path to the script from the site root. One can also provide a relative path from the current page. For instance, `src="script.js"` would mean a file `"script.js"` in the current folder.
You can also provide a relative path from the current page. For instance, `src="script.js"` would mean a file `"script.js"` in the current folder.
We can give a full URL as well. For instance: We can give a full URL as well. For instance:

View file

@ -4,7 +4,7 @@ For a long time, JavaScript evolved without compatibility issues. New features w
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever. That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever.
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`. This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most such modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`.
## "use strict" ## "use strict"
@ -19,9 +19,7 @@ For example:
... ...
``` ```
We will learn functions (a way to group commands) soon. We will learn functions (a way to group commands) soon. Looking ahead, let's note that `"use strict"` can be put at the start of most kinds of functions instead of the whole script. Doing that enables strict mode in that function only. But usually, people use it for the whole script.
Looking ahead, let's just note that `"use strict"` can be put at the start of most kinds of functions instead of the whole script. Doing that enables strict mode in that function only. But usually, people use it for the whole script.
````warn header="Ensure that \"use strict\" is at the top" ````warn header="Ensure that \"use strict\" is at the top"

View file

@ -1,4 +1,4 @@
First, the variable for the name of our planet. ## The variable for our planet
That's simple: That's simple:
@ -8,7 +8,7 @@ let ourPlanetName = "Earth";
Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong. Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
Second, the name of the current visitor: ## The name of the current visitor
```js ```js
let currentUserName = "John"; let currentUserName = "John";

View file

@ -2,4 +2,4 @@ We generally use upper case for constants that are "hard-coded". Or, in other wo
In this code, `birthday` is exactly like that. So we could use the upper case for it. In this code, `birthday` is exactly like that. So we could use the upper case for it.
In contrast, `age` is evaluated in run-time. Today we have one age, a year after we'll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit "less of a constant" than `birthday`, it is calculated, so we should keep the lower case for it. In contrast, `age` is evaluated in run-time. Today we have one age, a year after we'll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit "less of a constant" than `birthday`: it is calculated, so we should keep the lower case for it.

View file

@ -323,7 +323,7 @@ Modern JavaScript minifiers and browsers optimize code well enough, so it won't
We can declare variables to store data by using the `var`, `let`, or `const` keywords. We can declare variables to store data by using the `var`, `let`, or `const` keywords.
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8). - `let` -- is a modern variable declaration.
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them. - `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
- `const` -- is like `let`, but the value of the variable can't be changed. - `const` -- is like `let`, but the value of the variable can't be changed.

View file

@ -178,7 +178,7 @@ The `object` type is special.
All other types are called "primitive" because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We'll deal with them later in the chapter <info:object> after we learn more about primitives. All other types are called "primitive" because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We'll deal with them later in the chapter <info:object> after we learn more about primitives.
The `symbol` type is used to create unique identifiers for objects. We have to mention it here for completeness, but it's better to study this type after objects. The `symbol` type is used to create unique identifiers for objects. We mention it here for completeness, but we'll study ite after objects.
## The typeof operator [#type-typeof] ## The typeof operator [#type-typeof]

View file

@ -93,9 +93,7 @@ alert( +"" ); // 0
It actually does the same thing as `Number(...)`, but is shorter. It actually does the same thing as `Number(...)`, but is shorter.
The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?
What if we want to sum them?
The binary plus would add them as strings: The binary plus would add them as strings:

View file

@ -17,5 +17,5 @@ Some of the reasons:
3. Again, dictionary comparison, first char of `"2"` is greater than the first char of `"1"`. 3. Again, dictionary comparison, first char of `"2"` is greater than the first char of `"1"`.
4. Values `null` and `undefined` equal each other only. 4. Values `null` and `undefined` equal each other only.
5. Strict equality is strict. Different types from both sides lead to false. 5. Strict equality is strict. Different types from both sides lead to false.
6. See (4). 6. Similar to `(4)`, `null` only equals `undefined`.
7. Strict equality of different types. 7. Strict equality of different types.

View file

@ -138,11 +138,8 @@ The strict equality operator is a bit longer to write, but makes it obvious what
## Comparison with null and undefined ## Comparison with null and undefined
Let's see more edge cases.
There's a non-intuitive behavior when `null` or `undefined` are compared to other values. There's a non-intuitive behavior when `null` or `undefined` are compared to other values.
For a strict equality check `===` For a strict equality check `===`
: These values are different, because each of them is a different type. : These values are different, because each of them is a different type.

View file

@ -6,7 +6,7 @@ To do that, we can use the `if` statement and the conditional operator `?`, that
## The "if" statement ## The "if" statement
The `if` statement evaluates a condition and, if the condition's result is `true`, executes a block of code. The `if(...)` statement evaluates a condition in parentheses and, if the result is `true`, executes a block of code.
For example: For example:
@ -216,7 +216,7 @@ Depending on the condition `company == 'Netscape'`, either the first or the seco
We don't assign a result to a variable here. Instead, we execute different code depending on the condition. We don't assign a result to a variable here. Instead, we execute different code depending on the condition.
**We don't recommend using the question mark operator in this way.** **It's not recommended to use the question mark operator in this way.**
The notation is shorter than the equivalent `if` statement, which appeals to some programmers. But it is less readable. The notation is shorter than the equivalent `if` statement, which appeals to some programmers. But it is less readable.

View file

@ -10,7 +10,7 @@ if (userName == 'Admin') {
if (pass == 'TheMaster') { if (pass == 'TheMaster') {
alert( 'Welcome!' ); alert( 'Welcome!' );
} else if (pass == '' || pass == null) { } else if (pass == '' || pass == null) {
alert( 'Canceled.' ); alert( 'Canceled' );
} else { } else {
alert( 'Wrong password' ); alert( 'Wrong password' );
} }

View file

@ -6,13 +6,13 @@ importance: 3
Write the code which asks for a login with `prompt`. Write the code which asks for a login with `prompt`.
If the visitor enters `"Admin"`, then `prompt` for a password, if the input is an empty line or `key:Esc` -- show "Canceled.", if it's another string -- then show "I don't know you". If the visitor enters `"Admin"`, then `prompt` for a password, if the input is an empty line or `key:Esc` -- show "Canceled", if it's another string -- then show "I don't know you".
The password is checked as follows: The password is checked as follows:
- If it equals "TheMaster", then show "Welcome!", - If it equals "TheMaster", then show "Welcome!",
- Another string -- show "Wrong password", - Another string -- show "Wrong password",
- For an empty string or cancelled input, show "Canceled." - For an empty string or cancelled input, show "Canceled"
The schema: The schema:

View file

@ -64,7 +64,7 @@ if (hour < 10 || hour > 18 || isWeekend) {
} }
``` ```
## OR finds the first truthy value ## OR "||" finds the first truthy value
The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript. The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript.
@ -186,7 +186,7 @@ if (1 && 0) { // evaluated as true && false
``` ```
## AND finds the first falsy value ## AND "&&" finds the first falsy value
Given multiple AND'ed values: Given multiple AND'ed values:

View file

@ -17,7 +17,7 @@ while (condition) {
} }
``` ```
While the `condition` is `true`, the `code` from the loop body is executed. While the `condition` is truthy, the `code` from the loop body is executed.
For instance, the loop below outputs `i` while `i < 3`: For instance, the loop below outputs `i` while `i < 3`:
@ -84,7 +84,7 @@ This form of syntax should only be used when you want the body of the loop to ex
## The "for" loop ## The "for" loop
The `for` loop is the most commonly used loop. The `for` loop is more complex, but it's also the most commonly used loop.
It looks like this: It looks like this:
@ -111,8 +111,8 @@ Let's examine the `for` statement part-by-part:
| step| `i++` | Executes after the body on each iteration but before the condition check. | | step| `i++` | Executes after the body on each iteration but before the condition check. |
| body | `alert(i)`| Runs again and again while the condition is truthy. | | body | `alert(i)`| Runs again and again while the condition is truthy. |
The general loop algorithm works like this: The general loop algorithm works like this:
``` ```
Run begin Run begin
→ (if condition → run body and run step) → (if condition → run body and run step)
@ -121,6 +121,8 @@ Run begin
→ ... → ...
``` ```
That is, `begin` executes once, and then it iterates: after each `condition` test, `body` and `step` are executed.
If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper. If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.
Here's exactly what happens in our case: Here's exactly what happens in our case:
@ -289,8 +291,7 @@ if (i > 5) {
(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here (i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here
``` ```
...it stops working. Code like this will give a syntax error: ...it stops working: there's a syntax error.
This is just another reason not to use the question mark operator `?` instead of `if`. This is just another reason not to use the question mark operator `?` instead of `if`.
```` ````
@ -358,12 +359,12 @@ for (let i = 0; i < 3; i++) { ... }
The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop. The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop.
````warn header="Labels are not a \"goto\"" ````warn header="Labels do not allow to \"jump\" anywhere"
Labels do not allow us to jump into an arbitrary place in the code. Labels do not allow us to jump into an arbitrary place in the code.
For example, it is impossible to do this: For example, it is impossible to do this:
```js ```js
break label; // jumps to label? No. break label; // doesn't jumps to the label below
label: for (...) label: for (...)
``` ```

View file

@ -4,14 +4,14 @@ For given strings though, a simple `'=='` works too.
```js no-beautify ```js no-beautify
if(browser == 'Edge') { if(browser == 'Edge') {
alert("You've got the Edge!"); alert("У вас браузер Edge!");
} else if (browser == 'Chrome' } else if (browser == 'Chrome'
|| browser == 'Firefox' || browser == 'Firefox'
|| browser == 'Safari' || browser == 'Safari'
|| browser == 'Opera') { || browser == 'Opera') {
alert( 'Okay we support these browsers too' ); alert( 'Мы поддерживаем и эти браузерыo' );
} else { } else {
alert( 'We hope that this page looks ok!' ); alert( 'Надеемся, что эта страница выглядит хорошо!' );
} }
``` ```

View file

@ -9,18 +9,17 @@ Write the code using `if..else` which would correspond to the following `switch`
```js ```js
switch (browser) { switch (browser) {
case 'Edge': case 'Edge':
alert( "You've got the Edge!" ); alert( "У вас браузер Edge!" );
break; break;
case 'Chrome': case 'Chrome':
case 'Firefox': case 'Firefox':
case 'Safari': case 'Safari':
case 'Opera': case 'Opera':
alert( 'Okay we support these browsers too' ); alert( 'Мы поддерживаем и эти браузеры' );
break; break;
default: default:
alert( 'We hope that this page looks ok!' ); alert( 'Надеемся, что эта страница выглядит хорошо!' );
} }
``` ```

View file

@ -13,7 +13,7 @@ function checkAge(age) {
if (age > 18) { if (age > 18) {
return true; return true;
} else { } else {
return confirm('Do you have your parents permission to access this page?'); return confirm('Did parents allow you?');
} }
} }
``` ```

View file

@ -14,10 +14,8 @@ let x = prompt("x?", '');
let n = prompt("n?", ''); let n = prompt("n?", '');
if (n < 1) { if (n < 1) {
alert(`Power ${n} is not supported, alert(`Степень ${n} не поддерживается, только целая, большая 0`);
use an integer greater than 0`);
} else { } else {
alert( pow(x, n) ); alert( pow(x, n) );
} }
``` ```

View file

@ -20,9 +20,13 @@ function showMessage() {
} }
``` ```
The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (empty in the example above) and finally the code of the function, also named "the function body", between curly braces. The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (comma-separated, empty in the example above) and finally the code of the function, also named "the function body", between curly braces.
![](function_basics.png) ```js
function name(parameters) {
...body...
}
```
Our new function can be called by its name: `showMessage()`. Our new function can be called by its name: `showMessage()`.
@ -205,12 +209,11 @@ function showMessage(from, text = anotherFunction()) {
``` ```
```smart header="Evaluation of default parameters" ```smart header="Evaluation of default parameters"
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter.
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter. This is in contrast to some other languages like Python, where any default parameters are evaluated only once during the initial interpretation. This is in contrast to some other languages like Python, where any default parameters are evaluated only once during the initial interpretation.
``` ```
````smart header="Default parameters old-style" ````smart header="Default parameters old-style"
Old editions of JavaScript did not support default parameters. So there are alternative ways to support them, that you can find mostly in the old scripts. Old editions of JavaScript did not support default parameters. So there are alternative ways to support them, that you can find mostly in the old scripts.

View file

@ -41,7 +41,7 @@ Please note that the last line does not run the function, because there are no p
In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code. In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.
It is a special value of course, in the sense that we can call it like `sayHi()`. Surely, a function is a special values, in the sense that we can call it like `sayHi()`.
But it's still a value. So we can work with it like with other kinds of values. But it's still a value. So we can work with it like with other kinds of values.
@ -61,9 +61,7 @@ sayHi(); // Hello // this still works too (why wouldn't it)
Here's what happens above in detail: Here's what happens above in detail:
1. The Function Declaration `(1)` creates the function and puts it into the variable named `sayHi`. 1. The Function Declaration `(1)` creates the function and puts it into the variable named `sayHi`.
2. Line `(2)` copies it into the variable `func`. 2. Line `(2)` copies it into the variable `func`. Please note again: there are no parentheses after `sayHi`. If there were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself.
Please note again: there are no parentheses after `sayHi`. If there were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself.
3. Now the function can be called as both `sayHi()` and `func()`. 3. Now the function can be called as both `sayHi()` and `func()`.
Note that we could also have used a Function Expression to declare `sayHi`, in the first line: Note that we could also have used a Function Expression to declare `sayHi`, in the first line:
@ -93,7 +91,7 @@ let sayHi = function() {
The answer is simple: The answer is simple:
- There's no need for `;` at the end of code blocks and syntax structures that use them like `if { ... }`, `for { }`, `function f { }` etc. - There's no need for `;` at the end of code blocks and syntax structures that use them like `if { ... }`, `for { }`, `function f { }` etc.
- A Function Expression is used inside the statement: `let sayHi = ...;`, as a value. It's not a code block. The semicolon `;` is recommended at the end of statements, no matter what is the value. So the semicolon here is not related to the Function Expression itself in any way, it just terminates the statement. - A Function Expression is used inside the statement: `let sayHi = ...;`, as a value. It's not a code block, but rather an assignment. The semicolon `;` is recommended at the end of statements, no matter what is the value. So the semicolon here is not related to the Function Expression itself, it just terminates the statement.
```` ````
## Callback functions ## Callback functions
@ -210,7 +208,6 @@ That's due to internal algorithms. When JavaScript prepares to run the script, i
And after all Function Declarations are processed, the code is executed. So it has access to these functions. And after all Function Declarations are processed, the code is executed. So it has access to these functions.
For example, this works: For example, this works:
```js run refresh untrusted ```js run refresh untrusted
@ -239,6 +236,8 @@ let sayHi = function(name) { // (*) no magic any more
Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late. Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late.
Another special feature of Function Declarations is their block scope.
**In strict mode, when a Function Declaration is within a code block, it's visible everywhere inside that block. But not outside of it.** **In strict mode, when a Function Declaration is within a code block, it's visible everywhere inside that block. But not outside of it.**
For instance, let's imagine that we need to declare a function `welcome()` depending on the `age` variable that we get during runtime. And then we plan to use it some time later. For instance, let's imagine that we need to declare a function `welcome()` depending on the `age` variable that we get during runtime. And then we plan to use it some time later.
@ -291,7 +290,7 @@ if (age < 18) {
} else { } else {
function welcome() { // for age = 16, this "welcome" is never created function welcome() {
alert("Greetings!"); alert("Greetings!");
} }
} }
@ -308,7 +307,7 @@ What can we do to make `welcome` visible outside of `if`?
The correct approach would be to use a Function Expression and assign `welcome` to the variable that is declared outside of `if` and has the proper visibility. The correct approach would be to use a Function Expression and assign `welcome` to the variable that is declared outside of `if` and has the proper visibility.
Now it works as intended: This code works as intended:
```js run ```js run
let age = prompt("What is your age?", 18); let age = prompt("What is your age?", 18);
@ -395,7 +394,7 @@ alert( sum(1, 2) ); // 3
``` ```
If we have only one argument, then parentheses can be omitted, making that even shorter: If we have only one argument, then parentheses around parameters can be omitted, making that even shorter:
```js run ```js run
// same as // same as

View file

@ -143,9 +143,9 @@ Assignments
: There is a simple assignment: `a = b` and combined ones like `a *= 2`. : There is a simple assignment: `a = b` and combined ones like `a *= 2`.
Bitwise Bitwise
: Bitwise operators work with integers on bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed. : Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
Ternary Conditional
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`. : The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
Logical operators Logical operators
@ -245,7 +245,7 @@ We covered three ways to create a function in JavaScript:
let result = a + b; let result = a + b;
return result; return result;
} };
``` ```
Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function. Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function.
@ -277,8 +277,8 @@ We covered three ways to create a function in JavaScript:
| Function Declaration | Function Expression | | Function Declaration | Function Expression |
|----------------------|---------------------| |----------------------|---------------------|
| visible in the whole code block | created when the execution reaches it | | visible in the whole code block/script | created when the execution reaches it |
| - | can have a name, visible only inside the function | | | can have a name, visible only inside the function |
More: see <info:function-basics>, <info:function-expressions-arrows>. More: see <info:function-basics>, <info:function-expressions-arrows>.

Binary file not shown.