diff --git a/.gitattributes b/.gitattributes index 6313b56c5..d3877a538 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ * text=auto eol=lf +*.svg binary diff --git a/1-js/01-getting-started/1-intro/article.md b/1-js/01-getting-started/1-intro/article.md index 28a98a00a..4822fdb40 100644 --- a/1-js/01-getting-started/1-intro/article.md +++ b/1-js/01-getting-started/1-intro/article.md @@ -75,7 +75,7 @@ Examples of such restrictions include: This limitation is, again, for the user's safety. A page from `http://anysite.com` which a user has opened must not be able to access another browser tab with the URL `http://gmail.com` and steal information from there. - JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that's a safety limitation. -![](limitations.png) +![](limitations.svg) Such limits do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugin/extensions which may ask for extended permissions. @@ -92,8 +92,7 @@ JavaScript is the only browser technology that combines these three things. That's what makes JavaScript unique. That's why it's the most widespread tool for creating browser interfaces. -While planning to learn a new technology, it's beneficial to check its perspectives. So let's move on to the modern trends affecting it, including new languages and browser abilities. - +That said, JavaScript also allows to create servers, mobile applications, etc. ## Languages "over" JavaScript diff --git a/1-js/01-getting-started/1-intro/limitations.png b/1-js/01-getting-started/1-intro/limitations.png deleted file mode 100644 index 3ef6b1e08..000000000 Binary files a/1-js/01-getting-started/1-intro/limitations.png and /dev/null differ diff --git a/1-js/01-getting-started/1-intro/limitations.svg b/1-js/01-getting-started/1-intro/limitations.svg new file mode 100644 index 000000000..a7863c63c --- /dev/null +++ b/1-js/01-getting-started/1-intro/limitations.svg @@ -0,0 +1 @@ +https://javascript.info<script> ... </script>https://gmail.comhttps://javascript.info \ No newline at end of file diff --git a/1-js/01-getting-started/1-intro/limitations@2x.png b/1-js/01-getting-started/1-intro/limitations@2x.png deleted file mode 100644 index 7aa1c41ae..000000000 Binary files a/1-js/01-getting-started/1-intro/limitations@2x.png and /dev/null differ diff --git a/1-js/01-getting-started/2-manuals-specifications/article.md b/1-js/01-getting-started/2-manuals-specifications/article.md index f04cb96c7..754f4a8be 100644 --- a/1-js/01-getting-started/2-manuals-specifications/article.md +++ b/1-js/01-getting-started/2-manuals-specifications/article.md @@ -3,16 +3,15 @@ This book is a *tutorial*. It aims to help you gradually learn the language. But once you're familiar with the basics, you'll need other sources. - ## Specification -**The ECMA-262 specification** contains the most in-depth, detailed and formalized information about JavaScript. It defines the language. +[The ECMA-262 specification](https://www.ecma-international.org/publications/standards/Ecma-262.htm) contains the most in-depth, detailed and formalized information about JavaScript. It defines the language. -But being that formalized, it's difficult to understand at first. So if you need the most trustworthy source of information about the language details, it's the right place. But it's not for everyday use. +But being that formalized, it's difficult to understand at first. So if you need the most trustworthy source of information about the language details, the specification is the right place. But it's not for everyday use. The latest draft is at . -To read about bleeding-edge features, that are not yet widely supported, see proposals at . +To read about new bleeding-edge features, including those that are "almost standard" (so-called "stage 3"), see proposals at . Also, if you're in developing for the browser, then there are other specs covered in the [second part](info:browser-environment) of the tutorial. @@ -25,11 +24,11 @@ Also, if you're in developing for the browser, then there are other specs covere Although, it's often best to use an internet search instead. Just use "MDN [term]" in the query, e.g. to search for `parseInt` function. -- **MSDN** – Microsoft manual with a lot of information, including JavaScript (often referrerd to as JScript). If one needs something specific to Internet Explorer, better go there: . +- **MSDN** – Microsoft manual with a lot of information, including JavaScript (often referred to as JScript). If one needs something specific to Internet Explorer, better go there: . Also, we can use an internet search with phrases such as "RegExp MSDN" or "RegExp MSDN jscript". -## Feature support +## Compatibility tables JavaScript is a developing language, new features get added regularly. diff --git a/1-js/01-getting-started/4-devtools/article.md b/1-js/01-getting-started/4-devtools/article.md index ae5b3845d..c84d92704 100644 --- a/1-js/01-getting-started/4-devtools/article.md +++ b/1-js/01-getting-started/4-devtools/article.md @@ -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. -## 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. -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 diff --git a/1-js/01-getting-started/4-devtools/safari.png b/1-js/01-getting-started/4-devtools/safari.png index 37598a261..64c7a3f6c 100644 Binary files a/1-js/01-getting-started/4-devtools/safari.png and b/1-js/01-getting-started/4-devtools/safari.png differ diff --git a/1-js/01-getting-started/4-devtools/safari@2x.png b/1-js/01-getting-started/4-devtools/safari@2x.png index c59cebef2..27def4d09 100644 Binary files a/1-js/01-getting-started/4-devtools/safari@2x.png and b/1-js/01-getting-started/4-devtools/safari@2x.png differ diff --git a/1-js/02-first-steps/01-hello-world/article.md b/1-js/02-first-steps/01-hello-world/article.md index 4c384da19..489c01adf 100644 --- a/1-js/02-first-steps/01-hello-world/article.md +++ b/1-js/02-first-steps/01-hello-world/article.md @@ -1,6 +1,6 @@ # 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. @@ -46,7 +46,7 @@ The ` ``` -Here, `/path/to/script.js` is an absolute path to the script file (from the site root). - -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. +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. We can give a full URL as well. For instance: diff --git a/1-js/02-first-steps/01-hello-world/hello-world-render.png b/1-js/02-first-steps/01-hello-world/hello-world-render.png deleted file mode 100644 index ba94e017d..000000000 Binary files a/1-js/02-first-steps/01-hello-world/hello-world-render.png and /dev/null differ diff --git a/1-js/02-first-steps/01-hello-world/hello-world-render@2x.png b/1-js/02-first-steps/01-hello-world/hello-world-render@2x.png deleted file mode 100644 index 9b2d4479f..000000000 Binary files a/1-js/02-first-steps/01-hello-world/hello-world-render@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/03-strict-mode/article.md b/1-js/02-first-steps/03-strict-mode/article.md index 891b8fba3..573d76bc5 100644 --- a/1-js/02-first-steps/03-strict-mode/article.md +++ b/1-js/02-first-steps/03-strict-mode/article.md @@ -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. -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" @@ -19,9 +19,7 @@ For example: ... ``` -We will learn functions (a way to group commands) soon. - -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. +We will learn functions (a way to group commands) soon. Looking ahead, let's note that `"use strict"` can be put at the beginning of the function body 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" diff --git a/1-js/02-first-steps/04-variables/2-declare-variables/solution.md b/1-js/02-first-steps/04-variables/2-declare-variables/solution.md index 9ffc3efca..d56e54d28 100644 --- a/1-js/02-first-steps/04-variables/2-declare-variables/solution.md +++ b/1-js/02-first-steps/04-variables/2-declare-variables/solution.md @@ -1,4 +1,4 @@ -First, the variable for the name of our planet. +## The variable for our planet 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. -Second, the name of the current visitor: +## The name of the current visitor ```js let currentUserName = "John"; diff --git a/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md b/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md index f3a96c692..acd643fde 100644 --- a/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md +++ b/1-js/02-first-steps/04-variables/3-uppercast-constant/solution.md @@ -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 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. \ No newline at end of file +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. diff --git a/1-js/02-first-steps/04-variables/article.md b/1-js/02-first-steps/04-variables/article.md index e69befeda..80a36d9c9 100644 --- a/1-js/02-first-steps/04-variables/article.md +++ b/1-js/02-first-steps/04-variables/article.md @@ -12,7 +12,7 @@ A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "na To create a variable in JavaScript, use the `let` keyword. -The statement below creates (in other words: *declares* or *defines*) a variable with the name "message": +The statement below creates (in other words: *declares*) a variable with the name "message": ```js let message; @@ -99,7 +99,7 @@ We can easily grasp the concept of a "variable" if we imagine it as a "box" for For instance, the variable `message` can be imagined as a box labeled `"message"` with the value `"Hello!"` in it: -![](variable.png) +![](variable.svg) We can put any value in the box. @@ -116,7 +116,7 @@ alert(message); When the value is changed, the old data is removed from the variable: -![](variable-change.png) +![](variable-change.svg) We can also declare two variables and copy data from one into the other. @@ -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. -- `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 , just in case you need them. - `const` -- is like `let`, but the value of the variable can't be changed. diff --git a/1-js/02-first-steps/04-variables/variable-change.png b/1-js/02-first-steps/04-variables/variable-change.png deleted file mode 100644 index 9135e930a..000000000 Binary files a/1-js/02-first-steps/04-variables/variable-change.png and /dev/null differ diff --git a/1-js/02-first-steps/04-variables/variable-change.svg b/1-js/02-first-steps/04-variables/variable-change.svg new file mode 100644 index 000000000..427a6388c --- /dev/null +++ b/1-js/02-first-steps/04-variables/variable-change.svg @@ -0,0 +1 @@ +"World!""Hello!"message \ No newline at end of file diff --git a/1-js/02-first-steps/04-variables/variable-change@2x.png b/1-js/02-first-steps/04-variables/variable-change@2x.png deleted file mode 100644 index c9569e638..000000000 Binary files a/1-js/02-first-steps/04-variables/variable-change@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/04-variables/variable.png b/1-js/02-first-steps/04-variables/variable.png deleted file mode 100644 index 6d2482556..000000000 Binary files a/1-js/02-first-steps/04-variables/variable.png and /dev/null differ diff --git a/1-js/02-first-steps/04-variables/variable.svg b/1-js/02-first-steps/04-variables/variable.svg new file mode 100644 index 000000000..5d15c9e4e --- /dev/null +++ b/1-js/02-first-steps/04-variables/variable.svg @@ -0,0 +1 @@ +"Hello!"message \ No newline at end of file diff --git a/1-js/02-first-steps/04-variables/variable@2x.png b/1-js/02-first-steps/04-variables/variable@2x.png deleted file mode 100644 index 845f34408..000000000 Binary files a/1-js/02-first-steps/04-variables/variable@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/05-types/article.md b/1-js/02-first-steps/05-types/article.md index 0c9954ecf..0da617373 100644 --- a/1-js/02-first-steps/05-types/article.md +++ b/1-js/02-first-steps/05-types/article.md @@ -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 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 it after objects. ## The typeof operator [#type-typeof] @@ -221,7 +221,7 @@ The last three lines may need additional explanation: 1. `Math` is a built-in object that provides mathematical operations. We will learn it in the chapter . Here, it serves just as an example of an object. 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. -3. The result of `typeof alert` is `"function"`, because `alert` is a function of the language. We'll study functions in the next chapters where we'll see that there's no special "function" type in JavaScript. Functions belong to the object type. But `typeof` treats them differently. Formally, it's incorrect, but very convenient in practice. +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. ## Summary diff --git a/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/solution.md b/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/solution.md index 7dd0d61c2..4964a623a 100644 --- a/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/solution.md +++ b/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/solution.md @@ -14,6 +14,7 @@ true + false = 1 " -9 " - 5 = -14 // (4) null + 1 = 1 // (5) undefined + 1 = NaN // (6) +" \t \n" - 2 = -2 // (7) ``` 1. The addition with a string `"" + 1` converts `1` to a string: `"" + 1 = "1"`, and then we have `"1" + 0`, the same rule is applied. @@ -22,3 +23,4 @@ undefined + 1 = NaN // (6) 4. The subtraction always converts to numbers, so it makes `" -9 "` a number `-9` (ignoring spaces around it). 5. `null` becomes `0` after the numeric conversion. 6. `undefined` becomes `NaN` after the numeric conversion. +7. Space characters, are trimmed off string start and end when a string is converted to a number. Here the whole string consists of space characters, such as `\t`, `\n` and a "regular" space between them. So, similarly to an empty string, it becomes `0`. diff --git a/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/task.md b/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/task.md index f17e870de..930c71514 100644 --- a/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/task.md +++ b/1-js/02-first-steps/06-type-conversions/1-primitive-conversions-questions/task.md @@ -21,6 +21,7 @@ true + false " -9 " - 5 null + 1 undefined + 1 +" \t \n" - 2 ``` Think well, write down and then compare with the answer. diff --git a/1-js/02-first-steps/06-type-conversions/article.md b/1-js/02-first-steps/06-type-conversions/article.md index 6ac695e84..e764536f0 100644 --- a/1-js/02-first-steps/06-type-conversions/article.md +++ b/1-js/02-first-steps/06-type-conversions/article.md @@ -10,7 +10,7 @@ There are also cases when we need to explicitly convert a value to the expected In this chapter, we won't cover objects. Instead, we'll study primitives first. Later, after we learn about objects, we'll see how object conversion works in the chapter . ``` -## ToString +## To String String conversion happens when we need the string form of a value. @@ -30,7 +30,7 @@ alert(typeof value); // string String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc. -## ToNumber +## To Number Numeric conversion happens in mathematical functions and expressions automatically. @@ -94,7 +94,7 @@ alert( '1' + 2 ); // '12' (string to the left) This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers. ```` -## ToBoolean +## To Boolean Boolean conversion is the simplest one. @@ -129,9 +129,9 @@ alert( Boolean(" ") ); // spaces, also true (any non-empty string is true) The three most widely used type conversions are to string, to number, and to boolean. -**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values. +**`To String`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values. -**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`. +**`To Number`** -- Occurs in math operations. Can be performed with `Number(value)`. The conversion follows the rules: @@ -142,7 +142,7 @@ The conversion follows the rules: |true / false | `1 / 0` | | `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. | -**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`. +**`To Boolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`. Follows the rules: diff --git a/1-js/02-first-steps/07-operators/article.md b/1-js/02-first-steps/07-operators/article.md index b3fbfd9bb..a1373eade 100644 --- a/1-js/02-first-steps/07-operators/article.md +++ b/1-js/02-first-steps/07-operators/article.md @@ -26,7 +26,7 @@ Before we move on, let's grasp some common terminology. alert( y - x ); // 2, binary minus subtracts values ``` - Formally, we're talking about two different operators here: the unary negation (single operand: reverses the sign) and the binary subtraction (two operands: subtracts). + Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction operator, a binary operator that subtracts one number from another. ## String concatenation, binary + @@ -93,9 +93,7 @@ alert( +"" ); // 0 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. - -What if we want to sum them? +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? The binary plus would add them as strings: @@ -253,14 +251,14 @@ So, there are special operators for it: ```js run no-beautify let counter = 2; - counter++; // works the same as counter = counter + 1, but is shorter + counter++; // works the same as counter = counter + 1, but is shorter alert( counter ); // 3 ``` - **Decrement** `--` decreases a variable by 1: ```js run no-beautify let counter = 2; - counter--; // works the same as counter = counter - 1, but is shorter + counter--; // works the same as counter = counter - 1, but is shorter alert( counter ); // 1 ``` diff --git a/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md b/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md index 5c8bd2bc4..6437b512e 100644 --- a/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md +++ b/1-js/02-first-steps/08-comparison/1-comparison-questions/solution.md @@ -3,11 +3,11 @@ ```js no-beautify 5 > 4 → true "apple" > "pineapple" → false -"2" > "12" → true -undefined == null → true -undefined === null → false +"2" > "12" → true +undefined == null → true +undefined === null → false null == "\n0\n" → false -null === +"\n0\n" → false +null === +"\n0\n" → false ``` Some of the reasons: @@ -17,5 +17,5 @@ Some of the reasons: 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. 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. diff --git a/1-js/02-first-steps/08-comparison/article.md b/1-js/02-first-steps/08-comparison/article.md index 8697076a4..d889b1328 100644 --- a/1-js/02-first-steps/08-comparison/article.md +++ b/1-js/02-first-steps/08-comparison/article.md @@ -74,7 +74,7 @@ alert( '2' > 1 ); // true, string '2' becomes a number 2 alert( '01' == 1 ); // true, string '01' becomes a number 1 ``` -For boolean values, `true` becomes `1` and `false` becomes `0`. +For boolean values, `true` becomes `1` and `false` becomes `0`. For example: @@ -138,11 +138,8 @@ The strict equality operator is a bit longer to write, but makes it obvious what ## 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. - For a strict equality check `===` : These values are different, because each of them is a different type. diff --git a/1-js/02-first-steps/09-alert-prompt-confirm/article.md b/1-js/02-first-steps/09-alert-prompt-confirm/article.md index c14e0c85a..8ba414e9c 100644 --- a/1-js/02-first-steps/09-alert-prompt-confirm/article.md +++ b/1-js/02-first-steps/09-alert-prompt-confirm/article.md @@ -30,7 +30,7 @@ The function `prompt` accepts two arguments: result = prompt(title, [default]); ``` -It shows a modal window with a text message, an input field for the visitor, and the buttons OK/CANCEL. +It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel. `title` : The text to show the visitor. @@ -38,7 +38,7 @@ It shows a modal window with a text message, an input field for the visitor, and `default` : An optional second parameter, the initial value for the input field. -The visitor may type something in the prompt input field and press OK. Or they can cancel the input by pressing CANCEL or hitting the `key:Esc` key. +The visitor may type something in the prompt input field and press OK. Or they can cancel the input by pressing Cancel or hitting the `key:Esc` key. The call to `prompt` returns the text from the input field or `null` if the input was canceled. @@ -74,7 +74,7 @@ The syntax: result = confirm(question); ``` -The function `confirm` shows a modal window with a `question` and two buttons: OK and CANCEL. +The function `confirm` shows a modal window with a `question` and two buttons: OK and Cancel. The result is `true` if OK is pressed and `false` otherwise. @@ -94,10 +94,10 @@ We covered 3 browser-specific functions to interact with visitors: : shows a message. `prompt` -: shows a message asking the user to input text. It returns the text or, if CANCEL or `key:Esc` is clicked, `null`. +: shows a message asking the user to input text. It returns the text or, if Cancel button or `key:Esc` is clicked, `null`. `confirm` -: shows a message and waits for the user to press "OK" or "CANCEL". It returns `true` for OK and `false` for CANCEL/`key:Esc`. +: shows a message and waits for the user to press "OK" or "Cancel". It returns `true` for OK and `false` for Cancel/`key:Esc`. All these methods are modal: they pause script execution and don't allow the visitor to interact with the rest of the page until the window has been dismissed. diff --git a/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.png b/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.png deleted file mode 100644 index 04fb1fb0b..000000000 Binary files a/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.png and /dev/null differ diff --git a/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.svg b/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.svg new file mode 100644 index 000000000..ea4d122f6 --- /dev/null +++ b/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2.svg @@ -0,0 +1 @@ +BeginYou don't know? “ECMAScript”!Right!What's the “official” name of JavaScript?OtherECMAScript \ No newline at end of file diff --git a/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2@2x.png b/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2@2x.png deleted file mode 100644 index 08226b790..000000000 Binary files a/1-js/02-first-steps/10-ifelse/2-check-standard/ifelse_task2@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/10-ifelse/2-check-standard/task.md b/1-js/02-first-steps/10-ifelse/2-check-standard/task.md index 46fe05dc9..a4d943245 100644 --- a/1-js/02-first-steps/10-ifelse/2-check-standard/task.md +++ b/1-js/02-first-steps/10-ifelse/2-check-standard/task.md @@ -8,7 +8,6 @@ Using the `if..else` construct, write the code which asks: 'What is the "officia If the visitor enters "ECMAScript", then output "Right!", otherwise -- output: "Didn't know? ECMAScript!" -![](ifelse_task2.png) +![](ifelse_task2.svg) [demo src="ifelse_task2"] - diff --git a/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/solution.md b/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/solution.md index 638ce81f1..ff32354fa 100644 --- a/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/solution.md +++ b/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/solution.md @@ -1,6 +1,6 @@ ```js -result = (a + b < 4) ? 'Below' : 'Over'; +let result = (a + b < 4) ? 'Below' : 'Over'; ``` diff --git a/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/task.md b/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/task.md index 684e239f2..6bdf8453e 100644 --- a/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/task.md +++ b/1-js/02-first-steps/10-ifelse/5-rewrite-if-question/task.md @@ -4,13 +4,14 @@ importance: 5 # Rewrite 'if' into '?' -Rewrite this `if` using the ternary operator `'?'`: +Rewrite this `if` using the conditional operator `'?'`: ```js +let result; + if (a + b < 4) { result = 'Below'; } else { result = 'Over'; } ``` - diff --git a/1-js/02-first-steps/10-ifelse/article.md b/1-js/02-first-steps/10-ifelse/article.md index 49c1fc041..30287ccba 100644 --- a/1-js/02-first-steps/10-ifelse/article.md +++ b/1-js/02-first-steps/10-ifelse/article.md @@ -6,7 +6,7 @@ To do that, we can use the `if` statement and the conditional operator `?`, that ## 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: @@ -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 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. diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.png b/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.png deleted file mode 100644 index 32f0d4b94..000000000 Binary files a/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.png and /dev/null differ diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.svg b/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.svg new file mode 100644 index 000000000..010a53a4a --- /dev/null +++ b/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task.svg @@ -0,0 +1 @@ +BeginCanceledCanceledWelcome!I don't know youWrong passwordWho's there?Password?CancelCancelAdminTheMasterOtherOther \ No newline at end of file diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task@2x.png b/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task@2x.png deleted file mode 100644 index c3867e62c..000000000 Binary files a/1-js/02-first-steps/11-logical-operators/9-check-login/ifelse_task@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md b/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md index b535650ec..a30db7aae 100644 --- a/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md +++ b/1-js/02-first-steps/11-logical-operators/9-check-login/solution.md @@ -10,7 +10,7 @@ if (userName == 'Admin') { if (pass == 'TheMaster') { alert( 'Welcome!' ); } else if (pass == '' || pass == null) { - alert( 'Canceled.' ); + alert( 'Canceled' ); } else { alert( 'Wrong password' ); } diff --git a/1-js/02-first-steps/11-logical-operators/9-check-login/task.md b/1-js/02-first-steps/11-logical-operators/9-check-login/task.md index 780e674a9..290a52642 100644 --- a/1-js/02-first-steps/11-logical-operators/9-check-login/task.md +++ b/1-js/02-first-steps/11-logical-operators/9-check-login/task.md @@ -6,17 +6,17 @@ importance: 3 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: - If it equals "TheMaster", then show "Welcome!", - 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: -![](ifelse_task.png) +![](ifelse_task.svg) Please use nested `if` blocks. Mind the overall readability of the code. diff --git a/1-js/02-first-steps/11-logical-operators/article.md b/1-js/02-first-steps/11-logical-operators/article.md index 0773a10cb..25f8ff7f5 100644 --- a/1-js/02-first-steps/11-logical-operators/article.md +++ b/1-js/02-first-steps/11-logical-operators/article.md @@ -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. @@ -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: diff --git a/1-js/02-first-steps/12-while-for/article.md b/1-js/02-first-steps/12-while-for/article.md index c809581f5..580ac3e14 100644 --- a/1-js/02-first-steps/12-while-for/article.md +++ b/1-js/02-first-steps/12-while-for/article.md @@ -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`: @@ -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 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: @@ -108,11 +108,11 @@ Let's examine the `for` statement part-by-part: |-------|----------|----------------------------------------------------------------------------| | begin | `i = 0` | Executes once upon entering the loop. | | condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. | -| 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. | - +| step| `i++` | Executes after the body on each iteration. | The general loop algorithm works like this: + ``` Run begin → (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. 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 ``` -...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`. ```` @@ -299,7 +300,7 @@ This is just another reason not to use the question mark operator `?` instead of Sometimes we need to break out from multiple nested loops at once. -For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(3,3)`: +For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(2,2)`: ```js run no-beautify for (let i = 0; i < 3; i++) { @@ -308,8 +309,7 @@ for (let i = 0; i < 3; i++) { let input = prompt(`Value at coords (${i},${j})`, ''); - // what if I want to exit from here to Done (below)? - + // what if we want to exit from here to Done (below)? } } @@ -358,12 +358,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. -````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. For example, it is impossible to do this: ```js -break label; // jumps to label? No. +break label; // doesn't jumps to the label below label: for (...) ``` diff --git a/1-js/02-first-steps/13-switch/article.md b/1-js/02-first-steps/13-switch/article.md index 258f24068..dec40a537 100644 --- a/1-js/02-first-steps/13-switch/article.md +++ b/1-js/02-first-steps/13-switch/article.md @@ -125,7 +125,7 @@ switch (a) { break; *!* - case 3: // (*) grouped two cases + case 3: // (*) grouped two cases case 5: alert('Wrong!'); alert("Why don't you take a math class?"); diff --git a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md index 523bb127a..46da079c0 100644 --- a/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md +++ b/1-js/02-first-steps/14-function-basics/2-rewrite-function-question-or/task.md @@ -13,7 +13,7 @@ function checkAge(age) { if (age > 18) { return true; } else { - return confirm('Do you have your parents permission to access this page?'); + return confirm('Did parents allow you?'); } } ``` diff --git a/1-js/02-first-steps/14-function-basics/4-pow/solution.md b/1-js/02-first-steps/14-function-basics/4-pow/solution.md index 5ef20c386..19fe9011f 100644 --- a/1-js/02-first-steps/14-function-basics/4-pow/solution.md +++ b/1-js/02-first-steps/14-function-basics/4-pow/solution.md @@ -14,10 +14,8 @@ let x = prompt("x?", ''); let n = prompt("n?", ''); if (n < 1) { - alert(`Power ${n} is not supported, - use an integer greater than 0`); + alert(`Power ${n} is not supported, use a positive integer`); } else { alert( pow(x, n) ); } ``` - diff --git a/1-js/02-first-steps/14-function-basics/article.md b/1-js/02-first-steps/14-function-basics/article.md index ec34b744d..b1881e311 100644 --- a/1-js/02-first-steps/14-function-basics/article.md +++ b/1-js/02-first-steps/14-function-basics/article.md @@ -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()`. @@ -205,12 +209,11 @@ function showMessage(from, text = anotherFunction()) { ``` ```smart header="Evaluation of default parameters" +In JavaScript, a default parameter is evaluated every time the function is called without the respective 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. - +In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter. ``` - ````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. @@ -335,7 +338,19 @@ That doesn't work, because JavaScript assumes a semicolon after `return`. That'l return*!*;*/!* (some + long + expression + or + whatever * f(a) + f(b)) ``` -So, it effectively becomes an empty return. We should put the value on the same line instead. + +So, it effectively becomes an empty return. + +If we want the returned expression to wrap across multiple lines, we should start it at the same line as `return`. Or at least put the opening parentheses there as follows: + +```js +return ( + some + long + expression + + or + + whatever * f(a) + f(b) + ) +``` +And it will work just as we expect it to. ```` ## Naming a function [#function-naming] diff --git a/1-js/02-first-steps/14-function-basics/function_basics.png b/1-js/02-first-steps/14-function-basics/function_basics.png deleted file mode 100644 index f5e6f9418..000000000 Binary files a/1-js/02-first-steps/14-function-basics/function_basics.png and /dev/null differ diff --git a/1-js/02-first-steps/14-function-basics/function_basics@2x.png b/1-js/02-first-steps/14-function-basics/function_basics@2x.png deleted file mode 100644 index c31b2636a..000000000 Binary files a/1-js/02-first-steps/14-function-basics/function_basics@2x.png and /dev/null differ diff --git a/1-js/02-first-steps/15-function-expressions-arrows/article.md b/1-js/02-first-steps/15-function-expressions-arrows/article.md index 9b63907d5..d7f0f99ca 100644 --- a/1-js/02-first-steps/15-function-expressions-arrows/article.md +++ b/1-js/02-first-steps/15-function-expressions-arrows/article.md @@ -22,7 +22,6 @@ let sayHi = function() { Here, the function is created and assigned to the variable explicitly, like any other value. No matter how the function is defined, it's just a value stored in the variable `sayHi`. - The meaning of these code samples is the same: "create a function and put it into the variable `sayHi`". We can even print out that value using `alert`: @@ -41,7 +40,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. -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. @@ -61,21 +60,21 @@ sayHi(); // Hello // this still works too (why wouldn't it) Here's what happens above in detail: 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`. - - 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. +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. 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: ```js -let sayHi = function() { ... }; +let sayHi = function() { + alert( "Hello" ); +}; let func = sayHi; // ... ``` -Everything would work the same. Even more obvious what's going on, right? +Everything would work the same. ````smart header="Why is there a semicolon at the end?" @@ -93,7 +92,7 @@ let sayHi = function() { 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. -- 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 the value is. So the semicolon here is not related to the Function Expression itself, it just terminates the statement. ```` ## Callback functions @@ -133,11 +132,11 @@ function showCancel() { ask("Do you agree?", showOk, showCancel); ``` -Before we explore how we can write it in a much shorter way, let's note that in the browser (and on the server-side in some cases) such functions are quite popular. The major difference between a real-life implementation and the example above is that real-life functions use more complex ways to interact with the user than a simple `confirm`. In the browser, such a function usually draws a nice-looking question window. But that's another story. +In practice, such functions are quite useful. The major difference between a real-life `ask` and the example above is that real-life functions use more complex ways to interact with the user than a simple `confirm`. In the browser, such function usually draws a nice-looking question window. But that's another story. -**The arguments of `ask` are called *callback functions* or just *callbacks*.** +**The arguments `showOk` and `showCancel` of `ask` are called *callback functions* or just *callbacks*.** -The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, `showOk` becomes the callback for the "yes" answer, and `showCancel` for the "no" answer. +The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, `showOk` becomes the callback for "yes" answer, and `showCancel` for "no" answer. We can use Function Expressions to write the same function much shorter: @@ -156,12 +155,10 @@ ask( */!* ``` - Here, functions are declared right inside the `ask(...)` call. They have no name, and so are called *anonymous*. Such functions are not accessible outside of `ask` (because they are not assigned to variables), but that's just what we want here. Such code appears in our scripts very naturally, it's in the spirit of JavaScript. - ```smart header="A function is a value representing an \"action\"" Regular values like strings or numbers represent the *data*. @@ -196,19 +193,19 @@ First, the syntax: how to differentiate between them in the code. The more subtle difference is *when* a function is created by the JavaScript engine. -**A Function Expression is created when the execution reaches it and is usable from then on.** +**A Function Expression is created when the execution reaches it and is usable only from that moment.** Once the execution flow passes to the right side of the assignment `let sum = function…` -- here we go, the function is created and can be used (assigned, called, etc. ) from now on. Function Declarations are different. -**A Function Declaration is usable in the whole script (or a code block, if it's inside a block).** +**A Function Declaration can be called earlier than it is defined.** -In other words, when JavaScript *prepares* to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". +For example, a global Function Declaration is visible in the whole script, no matter where it is. -And after all of the Function Declarations are processed, the execution goes on. +That's due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an "initialization stage". -As a result, a function declared as a Function Declaration can be called earlier than it is defined. +And after all Function Declarations are processed, the code is executed. So it has access to these functions. For example, this works: @@ -224,7 +221,7 @@ function sayHi(name) { The Function Declaration `sayHi` is created when JavaScript is preparing to start the script and is visible everywhere in it. -...If it was a Function Expression, then it wouldn't work: +...If it were a Function Expression, then it wouldn't work: ```js run refresh untrusted *!* @@ -238,13 +235,13 @@ 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. -**When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.** +Another special feature of Function Declarations is their block scope. -Sometimes that's handy to declare a local function only needed in that block alone. But that feature may also cause problems. +**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. -The code below doesn't work: +If we use Function Declaration, it won't work as intended: ```js run let age = prompt("What is your age?", 18); @@ -292,7 +289,7 @@ if (age < 18) { } else { - function welcome() { // for age = 16, this "welcome" is never created + function welcome() { alert("Greetings!"); } } @@ -309,7 +306,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. -Now it works as intended: +This code works as intended: ```js run let age = prompt("What is your age?", 18); @@ -350,12 +347,12 @@ welcome(); // ok now ``` -```smart header="When should you choose Function Declaration versus Function Expression?" -As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax, the one we used before. It gives more freedom in how to organize our code, because we can call such functions before they are declared. +```smart header="When to choose Function Declaration versus Function Expression?" +As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared. -It's also a little bit easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching". +That's also better for readability, as it's easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching". -...But if a Function Declaration does not suit us for some reason (we've seen an example above), then Function Expression should be used. +...But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we've just seen an example), then Function Expression should be used. ``` @@ -396,7 +393,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 // same as @@ -456,7 +453,7 @@ alert( sum(1, 2) ); // 3 ```smart header="More to come" Here we praised arrow functions for brevity. But that's not all! Arrow functions have other interesting features. We'll return to them later in the chapter . -For now, we can already use them for one-line actions and callbacks. +For now, we can already use arrow functions for one-line actions and callbacks. ``` ## Summary @@ -467,7 +464,6 @@ For now, we can already use them for one-line actions and callbacks. - Function Declarations are processed before the code block is executed. They are visible everywhere in the block. - Function Expressions are created when the execution flow reaches them. - In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable. So we should use a Function Expression only when a Function Declaration is not fit for the task. We've seen a couple of examples of that in this chapter, and will see more in the future. diff --git a/1-js/02-first-steps/16-javascript-specials/article.md b/1-js/02-first-steps/16-javascript-specials/article.md index b1aefd1d4..b246a841c 100644 --- a/1-js/02-first-steps/16-javascript-specials/article.md +++ b/1-js/02-first-steps/16-javascript-specials/article.md @@ -53,7 +53,7 @@ To fully enable all features of modern JavaScript, we should start scripts with ... ``` -The directive must be at the top of a script or at the beginning of a function. +The directive must be at the top of a script or at the beginning of a function body. Without `"use strict"`, everything still works, but some features behave in the old-fashion, "compatible" way. We'd generally prefer the modern behavior. @@ -143,13 +143,13 @@ Assignments : There is a simple assignment: `a = b` and combined ones like `a *= 2`. 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`. Logical operators -: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped. Logical NOT `!` converts the operand to boolean type and returns the inverse value. +: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped (not necessary `true`/`false`). Logical NOT `!` converts the operand to boolean type and returns the inverse value. Comparisons : Equality check `==` for values of different types converts them to a number (except `null` and `undefined` that equal each other and nothing else), so these are equal: @@ -245,11 +245,9 @@ We covered three ways to create a function in JavaScript: let result = a + b; return result; - } + }; ``` - Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function. - 3. Arrow functions: ```js @@ -274,13 +272,7 @@ We covered three ways to create a function in JavaScript: - Parameters can have default values: `function sum(a = 1, b = 2) {...}`. - Functions always return something. If there's no `return` statement, then the result is `undefined`. - -| Function Declaration | Function Expression | -|----------------------|---------------------| -| visible in the whole code block | created when the execution reaches it | -| - | can have a name, visible only inside the function | - -More: see , . +Details: see , . ## More to come diff --git a/1-js/03-code-quality/01-debugging-chrome/article.md b/1-js/03-code-quality/01-debugging-chrome/article.md index 2ca0d7003..c777ae69f 100644 --- a/1-js/03-code-quality/01-debugging-chrome/article.md +++ b/1-js/03-code-quality/01-debugging-chrome/article.md @@ -2,27 +2,27 @@ Before writing more complex code, let's talk about debugging. -All modern browsers and most other environments support "debugging" -- a special UI in developer tools that makes finding and fixing errors much easier. +[Debugging](https://en.wikipedia.org/wiki/Debugging) is the process of finding and fixing errors within a script. All modern browsers and most other environments support debugging tools -- a special UI in developer tools that makes debugging much easier. It also allows to trace the code step by step to see what exactly is going on. -We'll be using Chrome here, because it's probably the most feature-rich in this aspect. +We'll be using Chrome here, because it has enough features, most other browsers have a similar process`. -## The "sources" pane +## The "Sources" panel Your Chrome version may look a little bit different, but it still should be obvious what's there. - Open the [example page](debugging/index.html) in Chrome. - Turn on developer tools with `key:F12` (Mac: `key:Cmd+Opt+I`). -- Select the `sources` pane. +- Select the `Sources` panel. Here's what you should see if you are doing it for the first time: -![](chrome-open-sources.png) +![](chrome-open-sources.svg) The toggler button opens the tab with files. Let's click it and select `hello.js` in the tree view. Here's what should show up: -![](chrome-tabs.png) +![](chrome-tabs.svg) Here we can see three zones: @@ -40,7 +40,7 @@ After a statement is executed, its result is shown below. For example, here `1+2` results in `3`, and `hello("debugger")` returns nothing, so the result is `undefined`: -![](chrome-sources-console.png) +![](chrome-sources-console.svg) ## Breakpoints @@ -50,14 +50,14 @@ Congratulations! You've set a breakpoint. Please also click on the number for li It should look like this (blue is where you should click): -![](chrome-sources-breakpoint.png) +![](chrome-sources-breakpoint.svg) A *breakpoint* is a point of code where the debugger will automatically pause the JavaScript execution. While the code is paused, we can examine current variables, execute commands in the console etc. In other words, we can debug it. -We can always find a list of breakpoints in the right pane. That's useful when we have many breakpoints in various files. It allows us to: -- Quickly jump to the breakpoint in the code (by clicking on it in the right pane). +We can always find a list of breakpoints in the right panel. That's useful when we have many breakpoints in various files. It allows us to: +- Quickly jump to the breakpoint in the code (by clicking on it in the right panel). - Temporarily disable the breakpoint by unchecking it. - Remove the breakpoint by right-clicking and selecting Remove. - ...And so on. @@ -70,7 +70,7 @@ That's handy when we need to stop only for a certain variable value or for certa ## Debugger command -We can also pause the code by using the `debugger` command, like this: +We can also pause the code by using the `debugger` command in it, like this: ```js function hello(name) { @@ -89,11 +89,11 @@ That's very convenient when we are in a code editor and don't want to switch to ## Pause and look around -In our example, `hello()` is called during the page load, so the easiest way to activate the debugger is to reload the page. So let's press `key:F5` (Windows, Linux) or `key:Cmd+R` (Mac). +In our example, `hello()` is called during the page load, so the easiest way to activate the debugger (after we've set the breakpoints) is to reload the page. So let's press `key:F5` (Windows, Linux) or `key:Cmd+R` (Mac). As the breakpoint is set, the execution pauses at the 4th line: -![](chrome-sources-debugger-pause.png) +![](chrome-sources-debugger-pause.svg) Please open the informational dropdowns to the right (labeled with arrows). They allow you to examine the current code state: @@ -105,7 +105,7 @@ Please open the informational dropdowns to the right (labeled with arrows). They At the current moment the debugger is inside `hello()` call, called by a script in `index.html` (no function there, so it's called "anonymous"). - If you click on a stack item, the debugger jumps to the corresponding code, and all its variables can be examined as well. + If you click on a stack item (e.g. "anonymous"), the debugger jumps to the corresponding code, and all its variables can be examined as well. 3. **`Scope` -- current variables.** `Local` shows local function variables. You can also see their values highlighted right over the source. @@ -118,16 +118,16 @@ Please open the informational dropdowns to the right (labeled with arrows). They Now it's time to *trace* the script. -There are buttons for it at the top of the right pane. Let's engage them. +There are buttons for it at the top of the right panel. Let's engage them. -- continue the execution, hotkey `key:F8`. : Resumes the execution. If there are no additional breakpoints, then the execution just continues and the debugger loses control. Here's what we can see after a click on it: - ![](chrome-sources-debugger-trace-1.png) + ![](chrome-sources-debugger-trace-1.svg) - The execution has resumed, reached another breakpoint inside `say()` and paused there. Take a look at the "Call stack" at the right. It has increased by one more call. We're inside `say()` now. + The execution has resumed, reached another breakpoint inside `say()` and paused there. Take a look at the "Call Stack" at the right. It has increased by one more call. We're inside `say()` now. -- make a step (run the next command), but *don't go into the function*, hotkey `key:F10`. : If we click it now, `alert` will be shown. The important thing is that `alert` can be any function, the execution "steps over it", skipping the function internals. @@ -147,23 +147,23 @@ There are buttons for it at the top of the right pane. Let's engage them. ```smart header="Continue to here" Right click on a line of code opens the context menu with a great option called "Continue to here". -That's handy when we want to move multiple steps forward, but we're too lazy to set a breakpoint. +That's handy when we want to move multiple steps forward to the line, but we're too lazy to set a breakpoint. ``` ## Logging -To output something to console, there's `console.log` function. +To output something to console from our code, there's `console.log` function. For instance, this outputs values from `0` to `4` to console: ```js run // open console to see for (let i = 0; i < 5; i++) { - console.log("value", i); + console.log("value,", i); } ``` -Regular users don't see that output, it is in the console. To see it, either open the Console tab of developer tools or press `key:Esc` while in another tab: that opens the console at the bottom. +Regular users don't see that output, it is in the console. To see it, either open the Console panel of developer tools or press `key:Esc` while in another panel: that opens the console at the bottom. If we have enough logging in our code, then we can see what's going on from the records, without the debugger. @@ -174,10 +174,10 @@ As we can see, there are three main ways to pause a script: 2. The `debugger` statements. 3. An error (if dev tools are open and the button is "on"). -Then we can examine variables and step on to see where the execution goes wrong. +When paused, we can debug - examine variables and trace the code to see where the execution goes wrong. There are many more options in developer tools than covered here. The full manual is at . The information from this chapter is enough to begin debugging, but later, especially if you do a lot of browser stuff, please go there and look through more advanced capabilities of developer tools. -Oh, and also you can click at various places of dev tools and just see what's showing up. That's probably the fastest route to learn dev tools. Don't forget about the right click as well! +Oh, and also you can click at various places of dev tools and just see what's showing up. That's probably the fastest route to learn dev tools. Don't forget about the right click and context menus! diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.png b/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.png deleted file mode 100644 index abc59905a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.svg new file mode 100644 index 000000000..73bcc484d --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources.svg @@ -0,0 +1 @@ +open sources \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources@2x.png deleted file mode 100644 index 546615e30..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-open-sources@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.png deleted file mode 100644 index caf60ebb6..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.svg new file mode 100644 index 000000000..580bf6384 --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint.svg @@ -0,0 +1 @@ +here's the listbreakpoints \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint@2x.png deleted file mode 100644 index 3f628b6ff..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-breakpoint@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.png deleted file mode 100644 index 0fc22b2ea..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.svg new file mode 100644 index 000000000..39f4f9177 --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console@2x.png deleted file mode 100644 index f01a7d101..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-console@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.png deleted file mode 100644 index 424ca26b0..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.svg new file mode 100644 index 000000000..40df82a32 --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause.svg @@ -0,0 +1 @@ +213jump to the outer functionwatch expressionscurrent variables \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause@2x.png deleted file mode 100644 index 04cc849d1..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-pause@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.png deleted file mode 100644 index 00507833a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.svg new file mode 100644 index 000000000..dc96ea4f7 --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1.svg @@ -0,0 +1 @@ +nested calls \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1@2x.png deleted file mode 100644 index d2a38bf0c..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-sources-debugger-trace-1@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.png b/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.png deleted file mode 100644 index df9e13f3f..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg b/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg new file mode 100644 index 000000000..4c7629231 --- /dev/null +++ b/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg @@ -0,0 +1 @@ +213 \ No newline at end of file diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome-tabs@2x.png deleted file mode 100644 index 5793bd059..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_break_error.png b/1-js/03-code-quality/01-debugging-chrome/chrome_break_error.png deleted file mode 100644 index 95399c7bb..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_break_error.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_break_error@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome_break_error@2x.png deleted file mode 100644 index d9d576ece..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_break_error@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources.png deleted file mode 100644 index 0482bbed5..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources@2x.png deleted file mode 100644 index fc65ed3fc..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break.png deleted file mode 100644 index ac8fb1ff5..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break@2x.png deleted file mode 100644 index d6eadbe6f..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_break@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint.png deleted file mode 100644 index 22fb9a5d5..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint@2x.png deleted file mode 100644 index eba2b9bfc..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_breakpoint@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons.png deleted file mode 100644 index 0f29946c3..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons@2x.png b/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons@2x.png deleted file mode 100644 index 7a16ea1c2..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/chrome_sources_buttons@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/console_error.png b/1-js/03-code-quality/01-debugging-chrome/console_error.png deleted file mode 100644 index ccf1b515a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/console_error.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/console_error@2x.png b/1-js/03-code-quality/01-debugging-chrome/console_error@2x.png deleted file mode 100644 index 4ab2fcea8..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/console_error@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage1.png b/1-js/03-code-quality/01-debugging-chrome/manage1.png deleted file mode 100644 index f624a1fd8..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage1.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage1@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage1@2x.png deleted file mode 100644 index 3f3c8116f..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage1@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage2.png b/1-js/03-code-quality/01-debugging-chrome/manage2.png deleted file mode 100644 index a038e3106..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage2.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage2@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage2@2x.png deleted file mode 100644 index 904280e49..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage2@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage3.png b/1-js/03-code-quality/01-debugging-chrome/manage3.png deleted file mode 100644 index 94bd7b31d..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage3.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage3@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage3@2x.png deleted file mode 100644 index 3a988aa2a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage3@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage4.png b/1-js/03-code-quality/01-debugging-chrome/manage4.png deleted file mode 100644 index 04f57c72d..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage4.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage4@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage4@2x.png deleted file mode 100644 index d8758709a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage4@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage5.png b/1-js/03-code-quality/01-debugging-chrome/manage5.png deleted file mode 100644 index 55355c37d..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage5.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage5@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage5@2x.png deleted file mode 100644 index c08f8a686..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage5@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage6.png b/1-js/03-code-quality/01-debugging-chrome/manage6.png deleted file mode 100644 index cdd9bd0ef..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage6.png and /dev/null differ diff --git a/1-js/03-code-quality/01-debugging-chrome/manage6@2x.png b/1-js/03-code-quality/01-debugging-chrome/manage6@2x.png deleted file mode 100644 index 52dad975a..000000000 Binary files a/1-js/03-code-quality/01-debugging-chrome/manage6@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/02-coding-style/article.md b/1-js/03-code-quality/02-coding-style/article.md index 05f24b6a9..bdcfec545 100644 --- a/1-js/03-code-quality/02-coding-style/article.md +++ b/1-js/03-code-quality/02-coding-style/article.md @@ -8,7 +8,7 @@ That is actually the art of programming -- to take a complex task and code it in Here is a cheat sheet with some suggested rules (see below for more details): -![](code-style.png) +![](code-style.svg) -![](figure-bracket-style.png) +For a very brief code, one line is allowed, e.g. `if (cond) return null`. But a code block (the last variant) is usually more readable. ### Line Length @@ -106,9 +112,9 @@ There are two types of indents: - **Horizontal indents: 2 or 4 spaces.** - A horizontal indentation is made using either 2 or 4 spaces or the "Tab" symbol. Which one to choose is an old holy war. Spaces are more common nowadays. + A horizontal indentation is made using either 2 or 4 spaces or the horizontal tab symbol (key `key:Tab`). Which one to choose is an old holy war. Spaces are more common nowadays. - One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the "Tab" symbol. + One advantage of spaces over tabs is that spaces allow more flexible configurations of indents than the tab symbol. For instance, we can align the arguments with the opening bracket, like this: @@ -153,7 +159,7 @@ If you're an experienced JavaScript programmer, you may choose a no-semicolon co Try to avoid nesting code too many levels deep. -For example, in the loop, it's sometimes a good idea to use the ["continue"](info:while-for#continue) directive to avoid extra nesting. +For example, in the loop, it's sometimes a good idea to use the [`continue`](info:while-for#continue) directive to avoid extra nesting. For example, instead of adding a nested `if` conditional like this: @@ -271,7 +277,7 @@ That's because when reading code, we first want to know *what it does*. If the c ## Style Guides -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. +A style guide contains general rules about "how to write" code, e.g. which quotes to use, how many spaces to indent, the maximal line length, etc. A lot of minor things. When all members of a team use the same style guide, the code looks uniform, regardless of which team member wrote it. diff --git a/1-js/03-code-quality/02-coding-style/code-style.png b/1-js/03-code-quality/02-coding-style/code-style.png deleted file mode 100644 index 1c6d355dd..000000000 Binary files a/1-js/03-code-quality/02-coding-style/code-style.png and /dev/null differ diff --git a/1-js/03-code-quality/02-coding-style/code-style.svg b/1-js/03-code-quality/02-coding-style/code-style.svg new file mode 100644 index 000000000..4cb4a8930 --- /dev/null +++ b/1-js/03-code-quality/02-coding-style/code-style.svg @@ -0,0 +1 @@ +2No space between the function name and parentheses between the parentheses and the parameterIndentation 2 spacesA space after for/if/while…} else { without a line breakSpaces around a nested callAn empty line between logical blocksLines are not very longA semicolon ; is mandatorySpaces around operatorsCurly brace { on the same line, after a spaceA space between parametersA space between parameters \ No newline at end of file diff --git a/1-js/03-code-quality/02-coding-style/code-style@2x.png b/1-js/03-code-quality/02-coding-style/code-style@2x.png deleted file mode 100644 index 832623d9c..000000000 Binary files a/1-js/03-code-quality/02-coding-style/code-style@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/02-coding-style/figure-bracket-style.png b/1-js/03-code-quality/02-coding-style/figure-bracket-style.png deleted file mode 100644 index b04db65c6..000000000 Binary files a/1-js/03-code-quality/02-coding-style/figure-bracket-style.png and /dev/null differ diff --git a/1-js/03-code-quality/02-coding-style/figure-bracket-style@2x.png b/1-js/03-code-quality/02-coding-style/figure-bracket-style@2x.png deleted file mode 100644 index 0e994ca4b..000000000 Binary files a/1-js/03-code-quality/02-coding-style/figure-bracket-style@2x.png and /dev/null differ diff --git a/1-js/03-code-quality/03-comments/article.md b/1-js/03-code-quality/03-comments/article.md index fabe3b783..29ba701f8 100644 --- a/1-js/03-code-quality/03-comments/article.md +++ b/1-js/03-code-quality/03-comments/article.md @@ -4,7 +4,7 @@ As we know from the chapter , comments can be single-line: start We normally use them to describe how and why the code works. -At first sight, commenting might be obvious, but novices in programming usually get it wrong. +At first sight, commenting might be obvious, but novices in programming often use them wrongly. ## Bad comments @@ -120,9 +120,9 @@ In reality, we can't totally avoid "explanatory" comments. There are complex alg So, explanatory comments are usually bad. Which comments are good? Describe the architecture -: Provide a high-level overview of components, how they interact, what's the control flow in various situations... In short -- the bird's eye view of the code. There's a special diagram language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) for high-level architecture diagrams. Definitely worth studying. +: Provide a high-level overview of components, how they interact, what's the control flow in various situations... In short -- the bird's eye view of the code. There's a special language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) to build high-level architecture diagrams explaining the code. Definitely worth studying. -Document a function usage +Document function parameters and usage : There's a special syntax [JSDoc](http://en.wikipedia.org/wiki/JSDoc) to document a function: usage, parameters, returned value. For instance: @@ -175,6 +175,6 @@ Good comments allow us to maintain the code well, come back to it after a delay **Avoid comments:** - That tell "how code works" and "what it does". -- Put them only if it's impossible to make the code so simple and self-descriptive that it doesn't require those. +- Put them in only if it's impossible to make the code so simple and self-descriptive that it doesn't require them. Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format). diff --git a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md index 7b58f0bf1..4d0571b9d 100644 --- a/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md +++ b/1-js/03-code-quality/05-testing-mocha/3-pow-test-wrong/solution.md @@ -4,7 +4,7 @@ What we have here is actually 3 tests, but layed out as a single function with 3 Sometimes it's easier to write this way, but if an error occurs, it's much less obvious what went wrong. -If an error happens inside a complex execution flow, then we'll have to figure out the data at that point. We'll actually have to *debug the test*. +If an error happens in the middle of a complex execution flow, then we'll have to figure out the data at that point. We'll actually have to *debug the test*. It would be much better to break the test into multiple `it` blocks with clearly written inputs and outputs. diff --git a/1-js/03-code-quality/05-testing-mocha/article.md b/1-js/03-code-quality/05-testing-mocha/article.md index c7b164b15..ca639fb62 100644 --- a/1-js/03-code-quality/05-testing-mocha/article.md +++ b/1-js/03-code-quality/05-testing-mocha/article.md @@ -1,8 +1,6 @@ -# Automated testing with mocha +# Automated testing with Mocha -Automated testing will be used in further tasks. - -It's actually a part of the "educational minimum" of a developer. +Automated testing will be used in further tasks, and it's also widely used in real projects. ## Why we need tests? @@ -20,15 +18,15 @@ For instance, we're creating a function `f`. Wrote some code, testing: `f(1)` wo That's very typical. When we develop something, we keep a lot of possible use cases in mind. But it's hard to expect a programmer to check all of them manually after every change. So it becomes easy to fix one thing and break another one. -**Automated testing means that tests are written separately, in addition to the code. They can be executed easily and check all the main use cases.** +**Automated testing means that tests are written separately, in addition to the code. They run our functions in various ways and compare results with the expected.** ## Behavior Driven Development (BDD) -Let's use a technique named [Behavior Driven Development](http://en.wikipedia.org/wiki/Behavior-driven_development) or, in short, BDD. That approach is used among many projects. BDD is not just about testing. That's more. +Let's start with a technique named [Behavior Driven Development](http://en.wikipedia.org/wiki/Behavior-driven_development) or, in short, BDD. **BDD is three things in one: tests AND documentation AND examples.** -Enough words. Let's see the example. +To understand BDD, we'll examine a practical case of development. ## Development of "pow": the spec @@ -38,7 +36,7 @@ That task is just an example: there's the `**` operator in JavaScript that can d Before creating the code of `pow`, we can imagine what the function should do and describe it. -Such description is called a *specification* or, in short, a spec, and looks like this: +Such description is called a *specification* or, in short, a spec, and contains descriptions of use cases together with tests for them, like this: ```js describe("pow", function() { @@ -53,17 +51,17 @@ describe("pow", function() { A spec has three main building blocks that you can see above: `describe("title", function() { ... })` -: What functionality we're describing. Uses to group "workers" -- the `it` blocks. In our case we're describing the function `pow`. +: What functionality we're describing. In our case we're describing the function `pow`. Used to group "workers" -- the `it` blocks. -`it("title", function() { ... })` +`it("use case description", function() { ... })` : In the title of `it` we *in a human-readable way* describe the particular use case, and the second argument is a function that tests it. `assert.equal(value1, value2)` : The code inside `it` block, if the implementation is correct, should execute without errors. - Functions `assert.*` are used to check whether `pow` works as expected. Right here we're using one of them -- `assert.equal`, it compares arguments and yields an error if they are not equal. Here it checks that the result of `pow(2, 3)` equals `8`. + Functions `assert.*` are used to check whether `pow` works as expected. Right here we're using one of them -- `assert.equal`, it compares arguments and yields an error if they are not equal. Here it checks that the result of `pow(2, 3)` equals `8`. There are other types of comparisons and checks, that we'll add later. - There are other types of comparisons and checks that we'll see further. +The specification can be executed, and it will run the test specified in `it` block. We'll see that later. ## The development flow @@ -71,7 +69,7 @@ The flow of development usually looks like this: 1. An initial spec is written, with tests for the most basic functionality. 2. An initial implementation is created. -3. To check whether it works, we run the testing framework [Mocha](http://mochajs.org/) (more details soon) that runs the spec. Errors are displayed. We make corrections until everything works. +3. To check whether it works, we run the testing framework [Mocha](http://mochajs.org/) (more details soon) that runs the spec. While the functionality is not complete, errors are displayed. We make corrections until everything works. 4. Now we have a working initial implementation with tests. 5. We add more use cases to the spec, probably not yet supported by the implementations. Tests start to fail. 6. Go to 3, update the implementation till tests give no errors. @@ -79,7 +77,9 @@ The flow of development usually looks like this: So, the development is *iterative*. We write the spec, implement it, make sure tests pass, then write more tests, make sure they work etc. At the end we have both a working implementation and tests for it. -In our case, the first step is complete: we have an initial spec for `pow`. So let's make an implementation. But before that let's make a "zero" run of the spec, just to see that tests are working (they will all fail). +Let's see this development flow in our practical case. + +The first step is already complete: we have an initial spec for `pow`. Now, before making the implementaton, let's use few JavaScript libraries to run the tests, just to see that they are working (they will all fail). ## The spec in action @@ -110,7 +110,7 @@ The result: As of now, the test fails, there's an error. That's logical: we have an empty function code in `pow`, so `pow(2,3)` returns `undefined` instead of `8`. -For the future, let's note that there are advanced test-runners, like [karma](https://karma-runner.github.io/) and others. So it's generally not a problem to setup many different tests. +For the future, let's note that there are more high-level test-runners, like [karma](https://karma-runner.github.io/) and others, that make it easy to autorun many different tests. ## Initial implementation @@ -132,7 +132,7 @@ What we've done is definitely a cheat. The function does not work: an attempt to ...But the situation is quite typical, it happens in practice. Tests pass, but the function works wrong. Our spec is imperfect. We need to add more use cases to it. -Let's add one more test to see if `pow(3, 4) = 81`. +Let's add one more test to check that `pow(3, 4) = 81`. We can select one of two ways to organize the test here: @@ -296,7 +296,7 @@ Testing finished – after all tests (after) [edit src="beforeafter" title="Open the example in the sandbox."] -Usually, `beforeEach/afterEach` (`before/after`) are used to perform initialization, zero out counters or do something else between the tests (or test groups). +Usually, `beforeEach/afterEach` and `before/after` are used to perform initialization, zero out counters or do something else between the tests (or test groups). ```` ## Extending the spec @@ -336,10 +336,9 @@ The result with new tests: The newly added tests fail, because our implementation does not support them. That's how BDD is done: first we write failing tests, and then make an implementation for them. ```smart header="Other assertions" - Please note the assertion `assert.isNaN`: it checks for `NaN`. -There are other assertions in Chai as well, for instance: +There are other assertions in [Chai](http://chaijs.com) as well, for instance: - `assert.equal(value1, value2)` -- checks the equality `value1 == value2`. - `assert.strictEqual(value1, value2)` -- checks the strict equality `value1 === value2`. @@ -380,9 +379,9 @@ In BDD, the spec goes first, followed by implementation. At the end we have both The spec can be used in three ways: -1. **Tests** guarantee that the code works correctly. -2. **Docs** -- the titles of `describe` and `it` tell what the function does. -3. **Examples** -- the tests are actually working examples showing how a function can be used. +1. As **Tests** - they guarantee that the code works correctly. +2. As **Docs** -- the titles of `describe` and `it` tell what the function does. +3. As **Examples** -- the tests are actually working examples showing how a function can be used. With the spec, we can safely improve, change, even rewrite the function from scratch and make sure it still works right. @@ -390,23 +389,21 @@ That's especially important in large projects when a function is used in many pl Without tests, people have two ways: -1. To perform the change, no matter what. And then our users meet bugs and report them. If we can afford that. -2. Or people become afraid to modify such functions, if the punishment for errors is harsh. Then it becomes old, overgrown with cobwebs, no one wants to get into it, and that's not good. +1. To perform the change, no matter what. And then our users meet bugs, as we probably fail to check something manually. +2. Or, if the punishment for errors is harsh, as there are no tests, people become afraid to modify such functions, and then the code becomes outdated, no one wants to get into it. Not good for development. -**Automatically tested code is contrary to that!** +**Automatic testing helps to avoid these problems!** -If the project is covered with tests, there's just no such problem. We can run tests and see a lot of checks made in a matter of seconds. +If the project is covered with tests, there's just no such problem. After any changes, we can run tests and see a lot of checks made in a matter of seconds. **Besides, a well-tested code has better architecture.** -Naturally, that's because it's easier to change and improve it. But not only that. +Naturally, that's because auto-tested code is easier to modify and improve. But there's also another reason. To write tests, the code should be organized in such a way that every function has a clearly described task, well-defined input and output. That means a good architecture from the beginning. In real life that's sometimes not that easy. Sometimes it's difficult to write a spec before the actual code, because it's not yet clear how it should behave. But in general writing tests makes development faster and more stable. -## What now? - Later in the tutorial you will meet many tasks with tests baked-in. So you'll see more practical examples. Writing tests requires good JavaScript knowledge. But we're just starting to learn it. So, to settle down everything, as of now you're not required to write tests, but you should already be able to read them even if they are a little bit more complex than in this chapter. diff --git a/1-js/03-code-quality/06-polyfills/article.md b/1-js/03-code-quality/06-polyfills/article.md index f4df5998c..b399fd428 100644 --- a/1-js/03-code-quality/06-polyfills/article.md +++ b/1-js/03-code-quality/06-polyfills/article.md @@ -19,7 +19,7 @@ Here Babel comes to the rescue. Actually, there are two parts in Babel: -1. First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build system like [webpack](http://webpack.github.io/) provide means to run transpiler automatically on every code change, so that very easy to integrate into development process. +1. First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build systems like [webpack](http://webpack.github.io/) provide means to run transpiler automatically on every code change, so that very easy to integrate into development process. 2. Second, the polyfill. @@ -29,8 +29,8 @@ Actually, there are two parts in Babel: A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations. Two interesting polyfills are: - - [babel polyfill](https://babeljs.io/docs/usage/polyfill/) that supports a lot, but is big. - - [polyfill.io](http://polyfill.io) service that allows to load/construct polyfills on-demand, depending on the features we need. + - [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features. + - [polyfill.io](http://polyfill.io) service that provides a script with polyfills, depending on the features and user's browser. So, if we're going to use modern language features, a transpiler and a polyfill are necessary. diff --git a/1-js/04-object-basics/01-object/article.md b/1-js/04-object-basics/01-object/article.md index 980670439..120e8dde0 100644 --- a/1-js/04-object-basics/01-object/article.md +++ b/1-js/04-object-basics/01-object/article.md @@ -9,7 +9,7 @@ An object can be created with figure brackets `{…}` with an optional list of * We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file. -![](object.png) +![](object.svg) An empty object ("empty cabinet") can be created using one of two syntaxes: @@ -18,7 +18,7 @@ let user = new Object(); // "object constructor" syntax let user = {}; // "object literal" syntax ``` -![](object-user-empty.png) +![](object-user-empty.svg) Usually, the figure brackets `{...}` are used. That declaration is called an *object literal*. @@ -42,14 +42,14 @@ In the `user` object, there are two properties: The resulting `user` object can be imagined as a cabinet with two signed files labeled "name" and "age". -![user object](object-user.png) +![user object](object-user.svg) We can add, remove and read files from it any time. Property values are accessible using the dot notation: ```js -// get fields of the object: +// get property values of the object: alert( user.name ); // John alert( user.age ); // 30 ``` @@ -60,7 +60,7 @@ The value can be of any type. Let's add a boolean one: user.isAdmin = true; ``` -![user object 2](object-user-isadmin.png) +![user object 2](object-user-isadmin.svg) To remove a property, we can use `delete` operator: @@ -68,7 +68,7 @@ To remove a property, we can use `delete` operator: delete user.age; ``` -![user object 3](object-user-delete.png) +![user object 3](object-user-delete.svg) We can also use multiword property names, but then they must be quoted: @@ -80,7 +80,7 @@ let user = { }; ``` -![](object-user-props.png) +![](object-user-props.svg) The last property in the list may end with a comma: @@ -105,7 +105,6 @@ That's because the dot requires the key to be a valid variable identifier. That There's an alternative "square bracket notation" that works with any string: - ```js run let user = {}; @@ -130,7 +129,7 @@ let key = "likes birds"; user[key] = true; ``` -Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. The dot notation cannot be used in a similar way. +Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. For instance: @@ -146,6 +145,17 @@ let key = prompt("What do you want to know about the user?", "name"); alert( user[key] ); // John (if enter "name") ``` +The dot notation cannot be used in a similar way: + +```js run +let user = { + name: "John", + age: 30 +}; + +let key = "name"; +alert( user.key ) // undefined +``` ### Computed properties @@ -222,10 +232,11 @@ As we see from the code, the assignment to a primitive `5` is ignored. That can become a source of bugs and even vulnerabilities if we intend to store arbitrary key-value pairs in an object, and allow a visitor to specify the keys. -In that case the visitor may choose "__proto__" as the key, and the assignment logic will be ruined (as shown above). +In that case the visitor may choose `__proto__` as the key, and the assignment logic will be ruined (as shown above). There is a way to make objects treat `__proto__` as a regular property, which we'll cover later, but first we need to know more about objects. -There's also another data structure [Map](info:map-set-weakmap-weakset), that we'll learn in the chapter , which supports arbitrary keys. + +There's also another data structure [Map](info:map-set), that we'll learn in the chapter , which supports arbitrary keys. ```` @@ -311,7 +322,7 @@ alert( *!*key*/!* in user ); // true, takes the name from key and checks for suc ``` ````smart header="Using \"in\" for properties that store `undefined`" -Usually, the strict comparison `"=== undefined"` check works fine. But there's a special case when it fails, but `"in"` works correctly. +Usually, the strict comparison `"=== undefined"` check the property existance just fine. But there's a special case when it fails, but `"in"` works correctly. It's when an object property exists, but stores `undefined`: @@ -331,7 +342,6 @@ In the code above, the property `obj.test` technically exists. So the `in` opera Situations like this happen very rarely, because `undefined` is usually not assigned. We mostly use `null` for "unknown" or "empty" values. So the `in` operator is an exotic guest in the code. ```` - ## The "for..in" loop To walk over all keys of an object, there exists a special form of the loop: `for..in`. This is a completely different thing from the `for(;;)` construct that we studied before. @@ -464,7 +474,7 @@ let phrase = message; As a result we have two independent variables, each one is storing the string `"Hello!"`. -![](variable-copy-value.png) +![](variable-copy-value.svg) Objects are not like that. @@ -478,7 +488,7 @@ let user = { }; ``` -![](variable-contains-reference.png) +![](variable-contains-reference.svg) Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it. @@ -496,7 +506,7 @@ let admin = user; // copy the reference Now we have two variables, each one with the reference to the same object: -![](variable-copy-reference.png) +![](variable-copy-reference.svg) We can use any variable to access the cabinet and modify its contents: @@ -520,7 +530,7 @@ The equality `==` and strict equality `===` operators for objects work exactly t **Two objects are equal only if they are the same object.** -For instance, two variables reference the same object, they are equal: +For instance, if two variables reference the same object, they are equal: ```js run let a = {}; @@ -559,7 +569,7 @@ user.age = 25; // (*) alert(user.age); // 25 ``` -It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes the value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. +It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes only value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. The `const` would give an error if we try to set `user` to something else, for instance: diff --git a/1-js/04-object-basics/01-object/object-user-delete.png b/1-js/04-object-basics/01-object/object-user-delete.png deleted file mode 100644 index 8702675c8..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-delete.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-delete.svg b/1-js/04-object-basics/01-object/object-user-delete.svg new file mode 100644 index 000000000..87753bb14 --- /dev/null +++ b/1-js/04-object-basics/01-object/object-user-delete.svg @@ -0,0 +1 @@ +nameisAdminuser \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object-user-delete@2x.png b/1-js/04-object-basics/01-object/object-user-delete@2x.png deleted file mode 100644 index 698766bb0..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-delete@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-empty.png b/1-js/04-object-basics/01-object/object-user-empty.png deleted file mode 100644 index 6b1f27a69..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-empty.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-empty.svg b/1-js/04-object-basics/01-object/object-user-empty.svg new file mode 100644 index 000000000..df684a0a3 --- /dev/null +++ b/1-js/04-object-basics/01-object/object-user-empty.svg @@ -0,0 +1 @@ +emptyuser \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object-user-empty@2x.png b/1-js/04-object-basics/01-object/object-user-empty@2x.png deleted file mode 100644 index 5f261eca4..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-empty@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-isadmin.png b/1-js/04-object-basics/01-object/object-user-isadmin.png deleted file mode 100644 index 2ce66a49d..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-isadmin.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-isadmin.svg b/1-js/04-object-basics/01-object/object-user-isadmin.svg new file mode 100644 index 000000000..c7a24cc92 --- /dev/null +++ b/1-js/04-object-basics/01-object/object-user-isadmin.svg @@ -0,0 +1 @@ +nameageisAdminuser \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object-user-isadmin@2x.png b/1-js/04-object-basics/01-object/object-user-isadmin@2x.png deleted file mode 100644 index 4a15dac64..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-isadmin@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-props.png b/1-js/04-object-basics/01-object/object-user-props.png deleted file mode 100644 index b0486e900..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-props.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user-props.svg b/1-js/04-object-basics/01-object/object-user-props.svg new file mode 100644 index 000000000..cb9afc1ac --- /dev/null +++ b/1-js/04-object-basics/01-object/object-user-props.svg @@ -0,0 +1 @@ +nameagelikes birdsuser \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object-user-props@2x.png b/1-js/04-object-basics/01-object/object-user-props@2x.png deleted file mode 100644 index 20859fe91..000000000 Binary files a/1-js/04-object-basics/01-object/object-user-props@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user.png b/1-js/04-object-basics/01-object/object-user.png deleted file mode 100644 index 6215b8207..000000000 Binary files a/1-js/04-object-basics/01-object/object-user.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object-user.svg b/1-js/04-object-basics/01-object/object-user.svg new file mode 100644 index 000000000..69f7efd93 --- /dev/null +++ b/1-js/04-object-basics/01-object/object-user.svg @@ -0,0 +1 @@ +nameageuser \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object-user@2x.png b/1-js/04-object-basics/01-object/object-user@2x.png deleted file mode 100644 index c66fa5159..000000000 Binary files a/1-js/04-object-basics/01-object/object-user@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object.png b/1-js/04-object-basics/01-object/object.png deleted file mode 100644 index a853c9c39..000000000 Binary files a/1-js/04-object-basics/01-object/object.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/object.svg b/1-js/04-object-basics/01-object/object.svg new file mode 100644 index 000000000..5a4a49fb6 --- /dev/null +++ b/1-js/04-object-basics/01-object/object.svg @@ -0,0 +1 @@ +key1key2key3 \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/object@2x.png b/1-js/04-object-basics/01-object/object@2x.png deleted file mode 100644 index 12011ff5c..000000000 Binary files a/1-js/04-object-basics/01-object/object@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-contains-reference.png b/1-js/04-object-basics/01-object/variable-contains-reference.png deleted file mode 100644 index cdd53d0b2..000000000 Binary files a/1-js/04-object-basics/01-object/variable-contains-reference.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-contains-reference.svg b/1-js/04-object-basics/01-object/variable-contains-reference.svg new file mode 100644 index 000000000..dedb7eaaa --- /dev/null +++ b/1-js/04-object-basics/01-object/variable-contains-reference.svg @@ -0,0 +1 @@ +username \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/variable-contains-reference@2x.png b/1-js/04-object-basics/01-object/variable-contains-reference@2x.png deleted file mode 100644 index 070126198..000000000 Binary files a/1-js/04-object-basics/01-object/variable-contains-reference@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-copy-reference.png b/1-js/04-object-basics/01-object/variable-copy-reference.png deleted file mode 100644 index 287085842..000000000 Binary files a/1-js/04-object-basics/01-object/variable-copy-reference.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-copy-reference.svg b/1-js/04-object-basics/01-object/variable-copy-reference.svg new file mode 100644 index 000000000..f212c0853 --- /dev/null +++ b/1-js/04-object-basics/01-object/variable-copy-reference.svg @@ -0,0 +1 @@ +useradminname \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/variable-copy-reference@2x.png b/1-js/04-object-basics/01-object/variable-copy-reference@2x.png deleted file mode 100644 index e7b994c53..000000000 Binary files a/1-js/04-object-basics/01-object/variable-copy-reference@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-copy-value.png b/1-js/04-object-basics/01-object/variable-copy-value.png deleted file mode 100644 index c360a0e13..000000000 Binary files a/1-js/04-object-basics/01-object/variable-copy-value.png and /dev/null differ diff --git a/1-js/04-object-basics/01-object/variable-copy-value.svg b/1-js/04-object-basics/01-object/variable-copy-value.svg new file mode 100644 index 000000000..37b1fe86a --- /dev/null +++ b/1-js/04-object-basics/01-object/variable-copy-value.svg @@ -0,0 +1 @@ +"Hello!"message"Hello!"phras e \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/variable-copy-value@2x.png b/1-js/04-object-basics/01-object/variable-copy-value@2x.png deleted file mode 100644 index 323bc4622..000000000 Binary files a/1-js/04-object-basics/01-object/variable-copy-value@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/article.md b/1-js/04-object-basics/02-garbage-collection/article.md index 42d35e7b8..620cbc21a 100644 --- a/1-js/04-object-basics/02-garbage-collection/article.md +++ b/1-js/04-object-basics/02-garbage-collection/article.md @@ -38,7 +38,7 @@ let user = { }; ``` -![](memory-user-john.png) +![](memory-user-john.svg) Here the arrow depicts an object reference. The global variable `"user"` references the object `{name: "John"}` (we'll call it John for brevity). The `"name"` property of John stores a primitive, so it's painted inside the object. @@ -48,7 +48,7 @@ If the value of `user` is overwritten, the reference is lost: user = null; ``` -![](memory-user-john-lost.png) +![](memory-user-john-lost.svg) Now John becomes unreachable. There's no way to access it, no references to it. Garbage collector will junk the data and free the memory. @@ -67,7 +67,7 @@ let admin = user; */!* ``` -![](memory-user-john-admin.png) +![](memory-user-john-admin.svg) Now if we do the same: ```js @@ -102,7 +102,7 @@ Function `marry` "marries" two objects by giving them references to each other a The resulting memory structure: -![](family.png) +![](family.svg) As of now, all objects are reachable. @@ -113,19 +113,19 @@ delete family.father; delete family.mother.husband; ``` -![](family-delete-refs.png) +![](family-delete-refs.svg) It's not enough to delete only one of these two references, because all objects would still be reachable. But if we delete both, then we can see that John has no incoming reference any more: -![](family-no-father.png) +![](family-no-father.svg) Outgoing references do not matter. Only incoming ones can make an object reachable. So, John is now unreachable and will be removed from the memory with all its data that also became unaccessible. After garbage collection: -![](family-no-father-2.png) +![](family-no-father-2.svg) ## Unreachable island @@ -139,7 +139,7 @@ family = null; The in-memory picture becomes: -![](family-no-family.png) +![](family-no-family.svg) This example demonstrates how important the concept of reachability is. @@ -161,25 +161,25 @@ The following "garbage collection" steps are regularly performed: For instance, let our object structure look like this: -![](garbage-collection-1.png) +![](garbage-collection-1.svg) We can clearly see an "unreachable island" to the right side. Now let's see how "mark-and-sweep" garbage collector deals with it. The first step marks the roots: -![](garbage-collection-2.png) +![](garbage-collection-2.svg) Then their references are marked: -![](garbage-collection-3.png) +![](garbage-collection-3.svg) ...And their references, while possible: -![](garbage-collection-4.png) +![](garbage-collection-4.svg) Now the objects that could not be visited in the process are considered unreachable and will be removed: -![](garbage-collection-5.png) +![](garbage-collection-5.svg) That's the concept of how garbage collection works. diff --git a/1-js/04-object-basics/02-garbage-collection/family-delete-refs.png b/1-js/04-object-basics/02-garbage-collection/family-delete-refs.png deleted file mode 100644 index 05160890e..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-delete-refs.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-delete-refs.svg b/1-js/04-object-basics/02-garbage-collection/family-delete-refs.svg new file mode 100644 index 000000000..e30bf7e50 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/family-delete-refs.svg @@ -0,0 +1 @@ +<global variable>ObjectObjectwifefamilyname: "John"name: "Ann"motherObjectfatherhusband \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/family-delete-refs@2x.png b/1-js/04-object-basics/02-garbage-collection/family-delete-refs@2x.png deleted file mode 100644 index a92fc573b..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-delete-refs@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-family.png b/1-js/04-object-basics/02-garbage-collection/family-no-family.png deleted file mode 100644 index e60f9b88d..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-family.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-family.svg b/1-js/04-object-basics/02-garbage-collection/family-no-family.svg new file mode 100644 index 000000000..cb9458555 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/family-no-family.svg @@ -0,0 +1 @@ +<global>ObjectObjectfatherwifename: "John"name: "Ann"motherObjecthusbandfamily: null \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-family@2x.png b/1-js/04-object-basics/02-garbage-collection/family-no-family@2x.png deleted file mode 100644 index 754903706..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-family@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father-2.png b/1-js/04-object-basics/02-garbage-collection/family-no-father-2.png deleted file mode 100644 index 823d0a618..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-father-2.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father-2.svg b/1-js/04-object-basics/02-garbage-collection/family-no-father-2.svg new file mode 100644 index 000000000..37255e573 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/family-no-father-2.svg @@ -0,0 +1 @@ +Objectfamilyname: "Ann"motherObject<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father-2@2x.png b/1-js/04-object-basics/02-garbage-collection/family-no-father-2@2x.png deleted file mode 100644 index 9e100d522..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-father-2@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father.png b/1-js/04-object-basics/02-garbage-collection/family-no-father.png deleted file mode 100644 index 5ddb6f68f..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-father.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father.svg b/1-js/04-object-basics/02-garbage-collection/family-no-father.svg new file mode 100644 index 000000000..8e7f3025f --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/family-no-father.svg @@ -0,0 +1 @@ +ObjectObjectwifefamilyname: "John"name: "Ann"motherObject<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/family-no-father@2x.png b/1-js/04-object-basics/02-garbage-collection/family-no-father@2x.png deleted file mode 100644 index 868c748a0..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family-no-father@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family.png b/1-js/04-object-basics/02-garbage-collection/family.png deleted file mode 100644 index f37464e6c..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/family.svg b/1-js/04-object-basics/02-garbage-collection/family.svg new file mode 100644 index 000000000..376132609 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/family.svg @@ -0,0 +1 @@ +ObjectObjectfatherwifefamilyname: "John"name: "Ann"motherObjecthusband<global variable> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/family@2x.png b/1-js/04-object-basics/02-garbage-collection/family@2x.png deleted file mode 100644 index 4f5d47210..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/family@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.png deleted file mode 100644 index 5cfe664c3..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.svg b/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.svg new file mode 100644 index 000000000..50697c4bd --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/garbage-collection-1.svg @@ -0,0 +1 @@ +<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-1@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-1@2x.png deleted file mode 100644 index cf93a1605..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-1@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.png deleted file mode 100644 index 2bbe4241d..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.svg b/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.svg new file mode 100644 index 000000000..dc0868323 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/garbage-collection-2.svg @@ -0,0 +1 @@ +<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-2@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-2@2x.png deleted file mode 100644 index f4a7abb52..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-2@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.png deleted file mode 100644 index 665a22784..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.svg b/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.svg new file mode 100644 index 000000000..d5faadb31 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/garbage-collection-3.svg @@ -0,0 +1 @@ +<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-3@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-3@2x.png deleted file mode 100644 index 60d4059cc..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-3@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.png deleted file mode 100644 index 4ba6e17ec..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.svg b/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.svg new file mode 100644 index 000000000..373647767 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/garbage-collection-4.svg @@ -0,0 +1 @@ +<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-4@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-4@2x.png deleted file mode 100644 index 8ac09c80d..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-4@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.png deleted file mode 100644 index 35c8816dc..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.svg b/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.svg new file mode 100644 index 000000000..49e9c62be --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/garbage-collection-5.svg @@ -0,0 +1 @@ +<global>unreachables \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection-5@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection-5@2x.png deleted file mode 100644 index 4db0c1732..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection-5@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection.png deleted file mode 100644 index 013d0a48a..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/garbage-collection@2x.png b/1-js/04-object-basics/02-garbage-collection/garbage-collection@2x.png deleted file mode 100644 index 681f29e4b..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/garbage-collection@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.png deleted file mode 100644 index 9ddac3e29..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.svg b/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.svg new file mode 100644 index 000000000..9ad1d88bc --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin.svg @@ -0,0 +1 @@ +username: "John"Objectadmin<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin@2x.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin@2x.png deleted file mode 100644 index 9069781f2..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john-admin@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.png deleted file mode 100644 index ae1684b2d..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.svg b/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.svg new file mode 100644 index 000000000..e75b8d465 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost.svg @@ -0,0 +1 @@ +name: "John"Objectuser: null<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost@2x.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost@2x.png deleted file mode 100644 index c510380f9..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john-lost@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john.png deleted file mode 100644 index 2ad00b6cb..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john.png and /dev/null differ diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john.svg b/1-js/04-object-basics/02-garbage-collection/memory-user-john.svg new file mode 100644 index 000000000..f051391d8 --- /dev/null +++ b/1-js/04-object-basics/02-garbage-collection/memory-user-john.svg @@ -0,0 +1 @@ +username: "John"Object<global> \ No newline at end of file diff --git a/1-js/04-object-basics/02-garbage-collection/memory-user-john@2x.png b/1-js/04-object-basics/02-garbage-collection/memory-user-john@2x.png deleted file mode 100644 index f365ac036..000000000 Binary files a/1-js/04-object-basics/02-garbage-collection/memory-user-john@2x.png and /dev/null differ diff --git a/1-js/04-object-basics/03-symbol/article.md b/1-js/04-object-basics/03-symbol/article.md index bd02a97eb..a17f85fe2 100644 --- a/1-js/04-object-basics/03-symbol/article.md +++ b/1-js/04-object-basics/03-symbol/article.md @@ -3,11 +3,11 @@ By specification, object property keys may be either of string type, or of symbol type. Not numbers, not booleans, only strings or symbols, these two types. -Till now we've only seen strings. Now let's see the advantages that symbols can give us. +Till now we've been using only strings. Now let's see the benefits that symbols can give us. ## Symbols -"Symbol" value represents a unique identifier. +A "symbol" represents a unique identifier. A value of this type can be created using `Symbol()`: @@ -50,9 +50,9 @@ alert(id); // TypeError: Cannot convert a Symbol value to a string */!* ``` -That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not occasionally convert one into another. +That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not accidentally convert one into another. -If we really want to show a symbol, we need to call `.toString()` on it, like here: +If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here: ```js run let id = Symbol("id"); *!* @@ -60,7 +60,7 @@ alert(id.toString()); // Symbol(id), now it works */!* ``` -Or get `symbol.description` property to get the description only: +Or get `symbol.description` property to show the description only: ```js run let id = Symbol("id"); *!* @@ -72,23 +72,27 @@ alert(id.description); // id ## "Hidden" properties -Symbols allow us to create "hidden" properties of an object, that no other part of code can occasionally access or overwrite. +Symbols allow us to create "hidden" properties of an object, that no other part of code can accidentally access or overwrite. -For instance, if we're working with `user` objects, that belong to a third-party code and don't have any `id` field. We'd like to add identifiers to them. +For instance, if we're working with `user` objects, that belong to a third-party code. We'd like to add identifiers to them. Let's use a symbol key for it: ```js run -let user = { name: "John" }; +let user = { // belongs to another code + name: "John" +}; + let id = Symbol("id"); -user[id] = "ID Value"; +user[id] = 1; + alert( user[id] ); // we can access the data using the symbol as the key ``` What's the benefit of using `Symbol("id")` over a string `"id"`? -As `user` objects belongs to another code, and that code also works with them, we shouldn't just add any fields to it. That's unsafe. But a symbol cannot be accessed occasionally, the third-party code probably won't even see it, so it's probably all right to do. +As `user` objects belongs to another code, and that code also works with them, we shouldn't just add any fields to it. That's unsafe. But a symbol cannot be accessed accidentally, the third-party code probably won't even see it, so it's probably all right to do. Also, imagine that another script wants to have its own identifier inside `user`, for its own purposes. That may be another JavaScript library, so that the scripts are completely unaware of each other. @@ -108,13 +112,13 @@ There will be no conflict between our and their identifiers, because symbols are ```js run let user = { name: "John" }; -// our script uses "id" property -user.id = "ID Value"; +// Our script uses "id" property +user.id = "Our id value"; -// ...if later another script the uses "id" for its purposes... +// ...Another script also wants "id" for its purposes... user.id = "Their id value" -// boom! overwritten! it did not mean to harm the colleague, but did it! +// Boom! overwritten by another script! ``` ### Symbols in a literal @@ -129,7 +133,7 @@ let id = Symbol("id"); let user = { name: "John", *!* - [id]: 123 // not just "id: 123" + [id]: 123 // not "id: 123" */!* }; ``` @@ -192,9 +196,7 @@ alert( obj[0] ); // test (same property) ## Global symbols -As we've seen, usually all symbols are different, even if they have the same name. But sometimes we want same-named symbols to be same entities. - -For instance, different parts of our application want to access symbol `"id"` meaning exactly the same property. +As we've seen, usually all symbols are different, even if they have the same name. But sometimes we want same-named symbols to be same entities. For instance, different parts of our application want to access symbol `"id"` meaning exactly the same property. To achieve that, there exists a *global symbol registry*. We can create symbols in it and access them later, and it guarantees that repeated accesses by the same name return exactly the same symbol. @@ -230,22 +232,29 @@ For global symbols, not only `Symbol.for(key)` returns a symbol by name, but the For instance: ```js run +// get symbol by name let sym = Symbol.for("name"); let sym2 = Symbol.for("id"); -// get name from symbol +// get name by symbol alert( Symbol.keyFor(sym) ); // name alert( Symbol.keyFor(sym2) ); // id ``` The `Symbol.keyFor` internally uses the global symbol registry to look up the key for the symbol. So it doesn't work for non-global symbols. If the symbol is not global, it won't be able to find it and return `undefined`. +That said, any symbols have `description` property. + For instance: ```js run -alert( Symbol.keyFor(Symbol.for("name")) ); // name, global symbol +let globalSymbol = Symbol.for("name"); +let localSymbol = Symbol("name"); + +alert( Symbol.keyFor(globalSymbol) ); // name, global symbol +alert( Symbol.keyFor(localSymbol) ); // undefined, not global -alert( Symbol.keyFor(Symbol("name2")) ); // undefined, the argument isn't a global symbol +alert( localSymbol.description ); // name ``` ## System symbols @@ -275,10 +284,10 @@ Symbols are always different values, even if they have the same name. If we want Symbols have two main use cases: 1. "Hidden" object properties. - If we want to add a property into an object that "belongs" to another script or a library, we can create a symbol and use it as a property key. A symbolic property does not appear in `for..in`, so it won't be occasionally processed together with other properties. Also it won't be accessed directly, because another script does not have our symbol. So the property will be protected from occasional use or overwrite. + If we want to add a property into an object that "belongs" to another script or a library, we can create a symbol and use it as a property key. A symbolic property does not appear in `for..in`, so it won't be accidentally processed together with other properties. Also it won't be accessed directly, because another script does not have our symbol. So the property will be protected from accidental use or overwrite. So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties. 2. There are many system symbols used by JavaScript which are accessible as `Symbol.*`. We can use them to alter some built-in behaviors. For instance, later in the tutorial we'll use `Symbol.iterator` for [iterables](info:iterable), `Symbol.toPrimitive` to setup [object-to-primitive conversion](info:object-toprimitive) and so on. -Technically, symbols are not 100% hidden. There is a built-in method [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) that allows us to get all symbols. Also there is a method named [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) that returns *all* keys of an object including symbolic ones. So they are not really hidden. But most libraries, built-in methods and syntax constructs adhere to a common agreement that they are. And the one who explicitly calls the aforementioned methods probably understands well what he's doing. +Technically, symbols are not 100% hidden. There is a built-in method [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) that allows us to get all symbols. Also there is a method named [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) that returns *all* keys of an object including symbolic ones. So they are not really hidden. But most libraries, built-in functions and syntax constructs don't use these methods. diff --git a/1-js/04-object-basics/04-object-methods/article.md b/1-js/04-object-basics/04-object-methods/article.md index f449c8c25..3d83a2241 100644 --- a/1-js/04-object-basics/04-object-methods/article.md +++ b/1-js/04-object-basics/04-object-methods/article.md @@ -111,6 +111,7 @@ let user = { sayHi() { *!* + // "this" is the "current object" alert(this.name); */!* } @@ -176,7 +177,7 @@ function sayHi() { } ``` -The value of `this` is evaluated during the run-time, depending on the context. And it can be anything. +The value of `this` is evaluated during the run-time, depending on the context. For instance, here the same function is assigned to two different objects and has different "this" in the calls: @@ -257,9 +258,9 @@ user.hi(); // John (the simple call works) */!* ``` -On the last line there is a conditinal operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`. +On the last line there is a conditional operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`. -Then the method is immediately called with parentheses `()`. But it doesn't work right! +Then the method is immediately called with parentheses `()`. But it doesn't work correctly! As you can see, the call results in an error, because the value of `"this"` inside the call becomes `undefined`. @@ -353,7 +354,7 @@ That's a special feature of arrow functions, it's useful when we actually do not The value of `this` is defined at run-time. - When a function is declared, it may use `this`, but that `this` has no value until the function is called. -- That function can be copied between objects. +- A function can be copied between objects. - When a function is called in the "method" syntax: `object.method()`, the value of `this` during the call is `object`. Please note that arrow functions are special: they have no `this`. When `this` is accessed inside an arrow function, it is taken from outside. diff --git a/1-js/04-object-basics/05-object-toprimitive/article.md b/1-js/04-object-basics/05-object-toprimitive/article.md index a7270aa66..ca449e5fe 100644 --- a/1-js/04-object-basics/05-object-toprimitive/article.md +++ b/1-js/04-object-basics/05-object-toprimitive/article.md @@ -3,7 +3,7 @@ What happens when objects are added `obj1 + obj2`, subtracted `obj1 - obj2` or printed using `alert(obj)`? -In that case objects are auto-converted to primitives, and then the operation is carried out. +In that case, objects are auto-converted to primitives, and then the operation is carried out. In the chapter we've seen the rules for numeric, string and boolean conversions of primitives. But we left a gap for objects. Now, as we know about methods and symbols it becomes possible to fill it. @@ -15,9 +15,7 @@ In the chapter we've seen the rules for numeric, string We can fine-tune string and numeric conversion, using special object methods. -The conversion algorithm is called `ToPrimitive` in the [specification](https://tc39.github.io/ecma262/#sec-toprimitive). It's called with a "hint" that specifies the conversion type. - -There are three variants: +There are three variants of type conversion, so-called "hints", described in the [specification](https://tc39.github.io/ecma262/#sec-toprimitive): `"string"` : For an object-to-string conversion, when we're doing an operation on an object that expects a string, like `alert`: @@ -66,7 +64,7 @@ Please note -- there are only three hints. It's that simple. There is no "boolea **To do the conversion, JavaScript tries to find and call three object methods:** -1. Call `obj[Symbol.toPrimitive](hint)` if the method exists, +1. Call `obj[Symbol.toPrimitive](hint)` - the method with the symbolic key `Symbol.toPrimitive` (system symbol), if such method exists, 2. Otherwise if hint is `"string"` - try `obj.toString()` and `obj.valueOf()`, whatever exists. 3. Otherwise if hint is `"number"` or `"default"` @@ -78,9 +76,9 @@ Let's start from the first method. There's a built-in symbol named `Symbol.toPri ```js obj[Symbol.toPrimitive] = function(hint) { - // return a primitive value + // must return a primitive value // hint = one of "string", "number", "default" -} +}; ``` For instance, here `user` object implements it: @@ -138,7 +136,9 @@ alert(+user); // valueOf -> 1000 alert(user + 500); // valueOf -> 1500 ``` -Often we want a single "catch-all" place to handle all primitive conversions. In this case we can implement `toString` only, like this: +As we can see, the behavior is the same as the previous example with `Symbol.toPrimitive`. + +Often we want a single "catch-all" place to handle all primitive conversions. In this case, we can implement `toString` only, like this: ```js run let user = { @@ -171,53 +171,40 @@ In contrast, `Symbol.toPrimitive` *must* return a primitive, otherwise there wil ## Further operations -An operation that initiated the conversion gets that primitive, and then continues to work with it, applying further conversions if necessary. +An operation that initiated the conversion gets the primitive, and then continues to work with it, applying further conversions if necessary. For instance: -- Mathematical operations (except binary plus) perform `ToNumber` conversion: +- Mathematical operations, except binary plus, convert the primitive to a number: ```js run let obj = { - toString() { // toString handles all conversions in the absence of other methods - return "2"; - } - }; - - alert(obj * 2); // 4, ToPrimitive gives "2", then it becomes 2 - ``` - -- Binary plus checks the primitive -- if it's a string, then it does concatenation, otherwise it performs `ToNumber` and works with numbers. - - String example: - ```js run - let obj = { + // toString handles all conversions in the absence of other methods toString() { return "2"; } }; - alert(obj + 2); // 22 (ToPrimitive returned string => concatenation) + alert(obj * 2); // 4, object converted to primitive "2", then multiplication made it a number ``` - Number example: +- Binary plus will concatenate strings in the same situation: ```js run let obj = { toString() { - return true; + return "2"; } }; - alert(obj + 2); // 3 (ToPrimitive returned boolean, not string => ToNumber) + alert(obj + 2); // 22 (conversion to primitive returned a string => concatenation) ``` - ## Summary The object-to-primitive conversion is called automatically by many built-in functions and operators that expect a primitive as a value. There are 3 types (hints) of it: -- `"string"` (for `alert` and other string conversions) +- `"string"` (for `alert` and other operations that need a string) - `"number"` (for maths) - `"default"` (few operators) diff --git a/1-js/04-object-basics/06-constructor-new/3-accumulator/task.md b/1-js/04-object-basics/06-constructor-new/3-accumulator/task.md index 3362b5b4b..c2c44881e 100644 --- a/1-js/04-object-basics/06-constructor-new/3-accumulator/task.md +++ b/1-js/04-object-basics/06-constructor-new/3-accumulator/task.md @@ -17,8 +17,10 @@ Here's the demo of the code: ```js let accumulator = new Accumulator(1); // initial value 1 + accumulator.read(); // adds the user-entered value accumulator.read(); // adds the user-entered value + alert(accumulator.value); // shows the sum of these values ``` diff --git a/1-js/04-object-basics/06-constructor-new/article.md b/1-js/04-object-basics/06-constructor-new/article.md index 4a7922a70..4519051ce 100644 --- a/1-js/04-object-basics/06-constructor-new/article.md +++ b/1-js/04-object-basics/06-constructor-new/article.md @@ -148,10 +148,10 @@ function BigUser() { this.name = "John"; - return { name: "Godzilla" }; // <-- returns an object + return { name: "Godzilla" }; // <-- returns this object } -alert( new BigUser().name ); // Godzilla, got that object ^^ +alert( new BigUser().name ); // Godzilla, got that object ``` And here's an example with an empty `return` (or we could place a primitive after it, doesn't matter): @@ -161,10 +161,7 @@ function SmallUser() { this.name = "John"; - return; // finishes the execution, returns this - - // ... - + return; // <-- returns this } alert( new SmallUser().name ); // John @@ -215,6 +212,8 @@ john = { */ ``` +To create complex objects, there's a more advanced syntax, [classes](info:classes), that we'll cover later. + ## Summary - Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. diff --git a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md index 13b71b2fe..fd22a4653 100644 --- a/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md +++ b/1-js/05-data-types/01-primitives-methods/1-string-new-property/solution.md @@ -17,9 +17,7 @@ Why? Let's replay what's happening at line `(*)`: 1. When a property of `str` is accessed, a "wrapper object" is created. 2. In strict mode, writing into it is an error. -3. Otherwise, the operation with the property is carried on, the object gets the `test` property, but after that the "wrapper object" disappears. - -So, without strict mode, in the last line `str` has no trace of the property. +3. Otherwise, the operation with the property is carried on, the object gets the `test` property, but after that the "wrapper object" disappears, so in the last line `str` has no trace of the property. **This example clearly shows that primitives are not objects.** diff --git a/1-js/05-data-types/01-primitives-methods/article.md b/1-js/05-data-types/01-primitives-methods/article.md index bc94ef994..b358b27e9 100644 --- a/1-js/05-data-types/01-primitives-methods/article.md +++ b/1-js/05-data-types/01-primitives-methods/article.md @@ -1,8 +1,6 @@ # Methods of primitives -JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. - -They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer). +JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer). Let's look at the key distinctions between primitives and objects. @@ -35,7 +33,7 @@ Many built-in objects already exist, such as those that work with dates, errors, But, these features come with a cost! -Objects are "heavier" than primitives. They require additional resources to support the internal machinery. But as properties and methods are very useful in programming, JavaScript engines try to optimize them to reduce the additional burden. +Objects are "heavier" than primitives. They require additional resources to support the internal machinery. ## A primitive as an object @@ -84,7 +82,7 @@ We'll see more specific methods in chapters and . ````warn header="Constructors `String/Number/Boolean` are for internal use only" -Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`. +Some languages like Java allow us to explicitly create "wrapper objects" for primitives using a syntax like `new Number(1)` or `new Boolean(false)`. In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places. diff --git a/1-js/05-data-types/02-number/article.md b/1-js/05-data-types/02-number/article.md index 57162d752..634baf151 100644 --- a/1-js/05-data-types/02-number/article.md +++ b/1-js/05-data-types/02-number/article.md @@ -2,7 +2,7 @@ All numbers in JavaScript are stored in 64-bit format [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754-2008_revision), also known as "double precision floating point numbers". -Let's recap and expand upon what we currently know about them. +Let's expand upon what we currently know about them. ## More ways to write a number @@ -213,7 +213,7 @@ So, division by powers `10` is guaranteed to work well in the decimal system, bu There's just no way to store *exactly 0.1* or *exactly 0.2* using the binary system, just like there is no way to store one-third as a decimal fraction. -The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don't allow us to see that "tiny precision loss", so the number shows up as `0.3`. But beware, the loss still exists. +The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don't allow us to see that "tiny precision loss", but it exists. We can see this in action: ```js run diff --git a/1-js/05-data-types/03-string/1-ucfirst/solution.md b/1-js/05-data-types/03-string/1-ucfirst/solution.md index 527d3978c..f7a332d0d 100644 --- a/1-js/05-data-types/03-string/1-ucfirst/solution.md +++ b/1-js/05-data-types/03-string/1-ucfirst/solution.md @@ -6,7 +6,7 @@ But we can make a new string based on the existing one, with the uppercased firs let newStr = str[0].toUpperCase() + str.slice(1); ``` -There's a small problem though. If `str` is empty, then `str[0]` is undefined, so we'll get an error. +There's a small problem though. If `str` is empty, then `str[0]` is `undefined`, and as `undefined` doesn't have the `toUpperCase()` method, we'll get an error. There are two variants here: diff --git a/1-js/05-data-types/03-string/1-ucfirst/task.md b/1-js/05-data-types/03-string/1-ucfirst/task.md index c0e6ecac4..ed8a1e6a7 100644 --- a/1-js/05-data-types/03-string/1-ucfirst/task.md +++ b/1-js/05-data-types/03-string/1-ucfirst/task.md @@ -2,7 +2,7 @@ importance: 5 --- -# Uppercast the first character +# Uppercase the first character Write a function `ucFirst(str)` that returns the string `str` with the uppercased first character, for instance: diff --git a/1-js/05-data-types/03-string/article.md b/1-js/05-data-types/03-string/article.md index 2b45f0b73..3bde8bd57 100644 --- a/1-js/05-data-types/03-string/article.md +++ b/1-js/05-data-types/03-string/article.md @@ -17,7 +17,7 @@ let double = "double-quoted"; let backticks = `backticks`; ``` -Single and double quotes are essentially the same. Backticks, however, allow us to embed any expression into the string, including function calls: +Single and double quotes are essentially the same. Backticks, however, allow us to embed any expression into the string, by wrapping it in `${…}`: ```js run function sum(a, b) { @@ -39,9 +39,12 @@ let guestList = `Guests: alert(guestList); // a list of guests, multiple lines ``` -If we try to use single or double quotes in the same way, there will be an error: +Looks natural, right? But single or double quotes do not work this way. + +If we use them and try to use multiple lines, there'll be an error: + ```js run -let guestList = "Guests: // Error: Unexpected token ILLEGAL +let guestList = "Guests: // Error: Unexpected token ILLEGAL * John"; ``` @@ -49,10 +52,9 @@ Single and double quotes come from ancient times of language creation when the n Backticks also allow us to specify a "template function" before the first backtick. The syntax is: func`string`. The function `func` is called automatically, receives the string and embedded expressions and can process them. You can read more about it in the [docs](mdn:/JavaScript/Reference/Template_literals#Tagged_template_literals). This is called "tagged templates". This feature makes it easier to wrap strings into custom templating or other functionality, but it is rarely used. - ## Special characters -It is still possible to create multiline strings with single quotes by using a so-called "newline character", written as `\n`, which denotes a line break: +It is still possible to create multiline strings with single and double quotes by using a so-called "newline character", written as `\n`, which denotes a line break: ```js run let guestList = "Guests:\n * John\n * Pete\n * Mary"; @@ -60,39 +62,45 @@ let guestList = "Guests:\n * John\n * Pete\n * Mary"; alert(guestList); // a multiline list of guests ``` -For example, these two lines describe the same: +For example, these two lines are equal, just written differently: ```js run -alert( "Hello\nWorld" ); // two lines using a "newline symbol" +let str1 = "Hello\nWorld"; // two lines using a "newline symbol" // two lines using a normal newline and backticks -alert( `Hello -World` ); +let str2 = `Hello +World`; + +alert(str1 == str2); // true ``` -There are other, less common "special" characters as well. Here's the list: +There are other, less common "special" characters. + +Here's the full list: | Character | Description | |-----------|-------------| -|`\b`|Backspace| -|`\f`|Form feed| |`\n`|New line| -|`\r`|Carriage return| +|`\r`|Carriage return: not used alone. Windows text files use a combination of two characters `\r\n` to represent a line break. | +|`\'`, `\"`|Quotes| +|`\\`|Backslash| |`\t`|Tab| -|`\uNNNN`|A unicode symbol with the hex code `NNNN`, for instance `\u00A9` -- is a unicode for the copyright symbol `©`. It must be exactly 4 hex digits. | -|`\u{NNNNNNNN}`|Some rare characters are encoded with two unicode symbols, taking up to 4 bytes. This long unicode requires braces around it.| +|`\b`, `\f`, `\v`| Backspace, Form Feed, Vertical Tab -- kept for compatibility, not used nowadays. | +|`\xXX`|Unicode character with the given hexadecimal unicode `XX`, e.g. `'\x7A'` is the same as `'z'`.| +|`\uXXXX`|A unicode symbol with the hex code `XXXX` in UTF-16 encoding, for instance `\u00A9` -- is a unicode for the copyright symbol `©`. It must be exactly 4 hex digits. | +|`\u{X…XXXXXX}` (1 to 6 hex characters)|A unicode symbol with the given UTF-32 encoding. Some rare characters are encoded with two unicode symbols, taking 4 bytes. This way we can insert long codes. | Examples with unicode: ```js run alert( "\u00A9" ); // © -alert( "\u{20331}" ); // 佫, a rare chinese hieroglyph (long unicode) +alert( "\u{20331}" ); // 佫, a rare Chinese hieroglyph (long unicode) alert( "\u{1F60D}" ); // 😍, a smiling face symbol (another long unicode) ``` All special characters start with a backslash character `\`. It is also called an "escape character". -We would also use it if we want to insert a quote into the string. +We might also use it if we wanted to insert a quote into the string. For instance: @@ -102,7 +110,7 @@ alert( 'I*!*\'*/!*m the Walrus!' ); // *!*I'm*/!* the Walrus! As you can see, we have to prepend the inner quote by the backslash `\'`, because otherwise it would indicate the string end. -Of course, that refers only to the quotes that are the same as the enclosing ones. So, as a more elegant solution, we could switch to double quotes or backticks instead: +Of course, only to the quotes that are the same as the enclosing ones need to be escaped. So, as a more elegant solution, we could switch to double quotes or backticks instead: ```js run alert( `I'm the Walrus!` ); // I'm the Walrus! @@ -120,7 +128,6 @@ alert( `The backslash: \\` ); // The backslash: \ ## String length - The `length` property has the string length: ```js run @@ -189,7 +196,7 @@ For instance: ```js run let str = 'Hi'; -str = 'h' + str[1]; // replace the string +str = 'h' + str[1]; // replace the string alert( str ); // hi ``` @@ -242,10 +249,8 @@ let str = 'Widget with id'; alert( str.indexOf('id', 2) ) // 12 ``` - If we're interested in all occurrences, we can run `indexOf` in a loop. Every new call is made with the position after the previous match: - ```js run let str = 'As sly as a fox, as strong as an ox'; @@ -305,10 +310,11 @@ if (str.indexOf("Widget") != -1) { } ``` -````smart header="The bitwise NOT trick" +#### The bitwise NOT trick + One of the old tricks used here is the [bitwise NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT) `~` operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation. -For 32-bit integers the call `~n` means exactly the same as `-(n+1)` (due to IEEE-754 format). +In practice, that means a simple thing: for 32-bit integers `~n` equals `-(n+1)`. For instance: @@ -321,9 +327,9 @@ alert( ~-1 ); // 0, the same as -(-1+1) */!* ``` -As we can see, `~n` is zero only if `n == -1`. +As we can see, `~n` is zero only if `n == -1` (that's for any 32-bit signed integer `n`). -So, the test `if ( ~str.indexOf("...") )` is truthy that the result of `indexOf` is not `-1`. In other words, when there is a match. +So, the test `if ( ~str.indexOf("...") )` is truthy only if the result of `indexOf` is not `-1`. In other words, when there is a match. People use it to shorten `indexOf` checks: @@ -338,7 +344,10 @@ if (~str.indexOf("Widget")) { It is usually not recommended to use language features in a non-obvious way, but this particular trick is widely used in old code, so we should understand it. Just remember: `if (~str.indexOf(...))` reads as "if found". -```` + +To be precise though, as big numbers are truncated to 32 bits by `~` operator, there exist other numbers that give `0`, the smallest is `~4294967295=0`. That makes such check is correct only if a string is not that long. + +Right now we can see this trick only in the old code, as modern JavaScript provides `.includes` method (see below). ### includes, startsWith, endsWith @@ -355,15 +364,15 @@ alert( "Hello".includes("Bye") ); // false The optional second argument of `str.includes` is the position to start searching from: ```js run -alert( "Midget".includes("id") ); // true -alert( "Midget".includes("id", 3) ); // false, from position 3 there is no "id" +alert( "Widget".includes("id") ); // true +alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id" ``` The methods [str.startsWith](mdn:js/String/startsWith) and [str.endsWith](mdn:js/String/endsWith) do exactly what they say: ```js run alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid" -alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get" +alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get" ``` ## Getting a substring @@ -397,7 +406,6 @@ There are 3 methods in JavaScript to get a substring: `substring`, `substr` and alert( str.slice(-4, -1) ); // gif ``` - `str.substring(start [, end])` : Returns the part of the string *between* `start` and `end`. @@ -405,7 +413,6 @@ There are 3 methods in JavaScript to get a substring: `substring`, `substr` and For instance: - ```js run let str = "st*!*ring*/!*ify"; @@ -421,7 +428,6 @@ There are 3 methods in JavaScript to get a substring: `substring`, `substr` and Negative arguments are (unlike slice) not supported, they are treated as `0`. - `str.substr(start [, length])` : Returns the part of the string from `start`, with the given `length`. @@ -447,11 +453,10 @@ Let's recap these methods to avoid any confusion: | `substring(start, end)` | between `start` and `end` | negative values mean `0` | | `substr(start, length)` | from `start` get `length` characters | allows negative `start` | - ```smart header="Which one to choose?" All of them can do the job. Formally, `substr` has a minor drawback: it is described not in the core JavaScript specification, but in Annex B, which covers browser-only features that exist mainly for historical reasons. So, non-browser environments may fail to support it. But in practice it works everywhere. -The author finds themself using `slice` almost all the time. +Of the other two variants, `slice` is a little bit more flexible, it allows negative arguments and shorter to write. So, it's enough to remember solely `slice` of these three methods. ``` ## Comparing strings @@ -514,7 +519,7 @@ alert( str ); // ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜ ``` -See? Capital characters go first, then a few special ones, then lowercase characters. +See? Capital characters go first, then a few special ones, then lowercase characters, and `Ö` near the end of the output. Now it becomes obvious why `a > Z`. @@ -523,10 +528,9 @@ The characters are compared by their numeric code. The greater code means that t - All lowercase letters go after uppercase letters because their codes are greater. - Some letters like `Ö` stand apart from the main alphabet. Here, it's code is greater than anything from `a` to `z`. - ### Correct comparisons -The "right" algorithm to do string comparisons is more complex than it may seem, because alphabets are different for different languages. The same-looking letter may be located differently in different alphabets. +The "right" algorithm to do string comparisons is more complex than it may seem, because alphabets are different for different languages. So, the browser needs to know the language to compare. @@ -534,11 +538,11 @@ Luckily, all modern browsers (IE10- requires the additional library [Intl.JS](ht It provides a special method to compare strings in different languages, following their rules. -The call [str.localeCompare(str2)](mdn:js/String/localeCompare): +The call [str.localeCompare(str2)](mdn:js/String/localeCompare) returns an integer indicating whether `str` is less, equal or greater than `str2` according to the language rules: -- Returns `1` if `str` is greater than `str2` according to the language rules. -- Returns `-1` if `str` is less than `str2`. -- Returns `0` if they are equal. +- Returns a negative number if `str` is less than `str2`. +- Returns a positive number if `str` is greater than `str2`. +- Returns `0` if they are equivalent. For instance: @@ -546,7 +550,7 @@ For instance: alert( 'Österreich'.localeCompare('Zealand') ); // -1 ``` -This method actually has two additional arguments specified in [the documentation](mdn:js/String/localeCompare), which allows it to specify the language (by default taken from the environment) and setup additional rules like case sensitivity or should `"a"` and `"á"` be treated as the same etc. +This method actually has two additional arguments specified in [the documentation](mdn:js/String/localeCompare), which allows it to specify the language (by default taken from the environment, letter order depends on the language) and setup additional rules like case sensitivity or should `"a"` and `"á"` be treated as the same etc. ## Internals, Unicode @@ -558,7 +562,7 @@ You can skip the section if you don't plan to support them. ### Surrogate pairs -Most symbols have a 2-byte code. Letters in most european languages, numbers, and even most hieroglyphs, have a 2-byte representation. +All frequently used characters have 2-byte codes. Letters in most european languages, numbers, and even most hieroglyphs, have a 2-byte representation. But 2 bytes only allow 65536 combinations and that's not enough for every possible symbol. So rare symbols are encoded with a pair of 2-byte characters called "a surrogate pair". @@ -567,7 +571,7 @@ The length of such symbols is `2`: ```js run alert( '𝒳'.length ); // 2, MATHEMATICAL SCRIPT CAPITAL X alert( '😂'.length ); // 2, FACE WITH TEARS OF JOY -alert( '𩷶'.length ); // 2, a rare chinese hieroglyph +alert( '𩷶'.length ); // 2, a rare Chinese hieroglyph ``` Note that surrogate pairs did not exist at the time when JavaScript was created, and thus are not correctly processed by the language! @@ -576,7 +580,7 @@ We actually have a single symbol in each of the strings above, but the `length` `String.fromCodePoint` and `str.codePointAt` are few rare methods that deal with surrogate pairs right. They recently appeared in the language. Before them, there were only [String.fromCharCode](mdn:js/String/fromCharCode) and [str.charCodeAt](mdn:js/String/charCodeAt). These methods are actually the same as `fromCodePoint/codePointAt`, but don't work with surrogate pairs. -But, for instance, getting a symbol can be tricky, because surrogate pairs are treated as two characters: +Getting a symbol can be tricky, because surrogate pairs are treated as two characters: ```js run alert( '𝒳'[0] ); // strange symbols... @@ -604,7 +608,7 @@ In many languages there are symbols that are composed of the base character with For instance, the letter `a` can be the base character for: `àáâäãåā`. Most common "composite" character have their own code in the UTF-16 table. But not all of them, because there are too many possible combinations. -To support arbitrary compositions, UTF-16 allows us to use several unicode characters. The base character and one or many "mark" characters that "decorate" it. +To support arbitrary compositions, UTF-16 allows us to use several unicode characters: the base character followed by one or many "mark" characters that "decorate" it. For instance, if we have `S` followed by the special "dot above" character (code `\u0307`), it is shown as Ṡ. @@ -627,10 +631,12 @@ This provides great flexibility, but also an interesting problem: two characters For instance: ```js run -alert( 'S\u0307\u0323' ); // Ṩ, S + dot above + dot below -alert( 'S\u0323\u0307' ); // Ṩ, S + dot below + dot above +let s1 = 'S\u0307\u0323'; // Ṩ, S + dot above + dot below +let s2 = 'S\u0323\u0307'; // Ṩ, S + dot below + dot above -alert( 'S\u0307\u0323' == 'S\u0323\u0307' ); // false +alert( `s1: ${s1}, s2: ${s2}` ); + +alert( s1 == s2 ); // false though the characters look identical (?!) ``` To solve this, there exists a "unicode normalization" algorithm that brings each string to the single "normal" form. @@ -649,14 +655,13 @@ alert( "S\u0307\u0323".normalize().length ); // 1 alert( "S\u0307\u0323".normalize() == "\u1e68" ); // true ``` -In reality, this is not always the case. The reason being that the symbol `Ṩ` is "common enough", so UTF-16 creators included it in the main table and gave it the code. +In reality, this is not always the case. The reason being that the symbol `Ṩ` is "common enough", so UTF-16 creators included it in the main table and gave it the code. If you want to learn more about normalization rules and variants -- they are described in the appendix of the Unicode standard: [Unicode Normalization Forms](http://www.unicode.org/reports/tr15/), but for most practical purposes the information from this section is enough. - ## Summary -- There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions. +- There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions `${…}`. - Strings in JavaScript are encoded using UTF-16. - We can use special characters like `\n` and insert letters by their unicode using `\u...`. - To get a character, use: `[]`. @@ -669,6 +674,6 @@ There are several other helpful methods in strings: - `str.trim()` -- removes ("trims") spaces from the beginning and end of the string. - `str.repeat(n)` -- repeats the string `n` times. -- ...and more. See the [manual](mdn:js/String) for details. +- ...and more to be found in the [manual](mdn:js/String). -Strings also have methods for doing search/replace with regular expressions. But that topic deserves a separate chapter, so we'll return to that later. +Strings also have methods for doing search/replace with regular expressions. But that's big topic, so it's explained in a separate tutorial section . diff --git a/1-js/05-data-types/04-array/array-pop.png b/1-js/05-data-types/04-array/array-pop.png deleted file mode 100644 index 4d6867b14..000000000 Binary files a/1-js/05-data-types/04-array/array-pop.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/array-pop.svg b/1-js/05-data-types/04-array/array-pop.svg new file mode 100644 index 000000000..351916051 --- /dev/null +++ b/1-js/05-data-types/04-array/array-pop.svg @@ -0,0 +1 @@ +0123"Apple""Orange""Pear""Lemon"length = 4clear012"Apple""Orange""Pear"length = 3 \ No newline at end of file diff --git a/1-js/05-data-types/04-array/array-pop@2x.png b/1-js/05-data-types/04-array/array-pop@2x.png deleted file mode 100644 index c65ef9446..000000000 Binary files a/1-js/05-data-types/04-array/array-pop@2x.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/array-shift.png b/1-js/05-data-types/04-array/array-shift.png deleted file mode 100644 index 5798a6476..000000000 Binary files a/1-js/05-data-types/04-array/array-shift.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/array-shift.svg b/1-js/05-data-types/04-array/array-shift.svg new file mode 100644 index 000000000..09236b9d1 --- /dev/null +++ b/1-js/05-data-types/04-array/array-shift.svg @@ -0,0 +1 @@ +123"Orange""Pear""Lemon"length = 423"Orange""Pear""Lemon"length = 3clearmove elements to the left0"Apple"012"Orange""Pear""Lemon"11 \ No newline at end of file diff --git a/1-js/05-data-types/04-array/array-shift@2x.png b/1-js/05-data-types/04-array/array-shift@2x.png deleted file mode 100644 index ba95f2651..000000000 Binary files a/1-js/05-data-types/04-array/array-shift@2x.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/array-speed.png b/1-js/05-data-types/04-array/array-speed.png deleted file mode 100644 index a400d0c1d..000000000 Binary files a/1-js/05-data-types/04-array/array-speed.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/array-speed.svg b/1-js/05-data-types/04-array/array-speed.svg new file mode 100644 index 000000000..5660cd5ec --- /dev/null +++ b/1-js/05-data-types/04-array/array-speed.svg @@ -0,0 +1 @@ +0123popunshiftpushshift \ No newline at end of file diff --git a/1-js/05-data-types/04-array/array-speed@2x.png b/1-js/05-data-types/04-array/array-speed@2x.png deleted file mode 100644 index 11a3e67c9..000000000 Binary files a/1-js/05-data-types/04-array/array-speed@2x.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index c91a9e233..7dc54bd4b 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -100,7 +100,7 @@ A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of th - `push` appends an element to the end. - `shift` get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st. -![](queue.png) +![](queue.svg) Arrays support both operations. @@ -117,7 +117,7 @@ So new elements are added or taken always from the "end". A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top: -![](stack.png) +![](stack.svg) For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out). @@ -239,7 +239,7 @@ Please think of arrays as special structures to work with the *ordered data*. Th Methods `push/pop` run fast, while `shift/unshift` are slow. -![](array-speed.png) +![](array-speed.svg) Why is it faster to work with the end of an array than with its beginning? Let's see what happens during the execution: @@ -255,7 +255,7 @@ The `shift` operation must do 3 things: 2. Move all elements to the left, renumber them from the index `1` to `0`, from `2` to `1` and so on. 3. Update the `length` property. -![](array-shift.png) +![](array-shift.svg) **The more elements in the array, the more time to move them, more in-memory operations.** @@ -269,7 +269,7 @@ The actions for the `pop` operation: fruits.pop(); // take 1 element from the end ``` -![](array-pop.png) +![](array-pop.svg) **The `pop` method does not need to move anything, because other elements keep their indexes. That's why it's blazingly fast.** @@ -394,7 +394,7 @@ let matrix = [ [7, 8, 9] ]; -alert( matrix[1][1] ); // the central element +alert( matrix[1][1] ); // 5, the central element ``` ## toString diff --git a/1-js/05-data-types/04-array/queue.png b/1-js/05-data-types/04-array/queue.png deleted file mode 100644 index 39af3beda..000000000 Binary files a/1-js/05-data-types/04-array/queue.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/queue.svg b/1-js/05-data-types/04-array/queue.svg new file mode 100644 index 000000000..0ed2f1cd7 --- /dev/null +++ b/1-js/05-data-types/04-array/queue.svg @@ -0,0 +1 @@ +pushshift \ No newline at end of file diff --git a/1-js/05-data-types/04-array/queue@2x.png b/1-js/05-data-types/04-array/queue@2x.png deleted file mode 100644 index 75045a51d..000000000 Binary files a/1-js/05-data-types/04-array/queue@2x.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/stack.png b/1-js/05-data-types/04-array/stack.png deleted file mode 100644 index 7d2599355..000000000 Binary files a/1-js/05-data-types/04-array/stack.png and /dev/null differ diff --git a/1-js/05-data-types/04-array/stack.svg b/1-js/05-data-types/04-array/stack.svg new file mode 100644 index 000000000..dcc600e71 --- /dev/null +++ b/1-js/05-data-types/04-array/stack.svg @@ -0,0 +1 @@ +pushpop \ No newline at end of file diff --git a/1-js/05-data-types/04-array/stack@2x.png b/1-js/05-data-types/04-array/stack@2x.png deleted file mode 100644 index 16c622518..000000000 Binary files a/1-js/05-data-types/04-array/stack@2x.png and /dev/null differ diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md index 32d3b2679..b9d627a0a 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md @@ -36,4 +36,4 @@ So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 mill So the solution is only good for small arrays. -Further in the chapter we'll see how to optimize it. +Further in the chapter we'll see how to optimize it. diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/_js.view/solution.js b/1-js/05-data-types/05-array-methods/6-calculator-extendable/_js.view/solution.js index 50c40e804..45ef1619d 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/_js.view/solution.js @@ -1,6 +1,6 @@ function Calculator() { - let methods = { + this.methods = { "-": (a, b) => a - b, "+": (a, b) => a + b }; @@ -12,14 +12,14 @@ function Calculator() { op = split[1], b = +split[2] - if (!methods[op] || isNaN(a) || isNaN(b)) { + if (!this.methods[op] || isNaN(a) || isNaN(b)) { return NaN; } - return methods[op](a, b); + return this.methods[op](a, b); } this.addMethod = function(name, func) { - methods[name] = func; + this.methods[name] = func; }; } diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md index 41178663d..982d3f9ed 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md @@ -1,3 +1,5 @@ -- Please note how methods are stored. They are simply added to the internal object. +- Please note how methods are stored. They are simply added to `this.methods` property. - All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions. + +[js src="_js/solution.js"] diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md index cc5453ceb..e0d302f4c 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md @@ -31,6 +31,6 @@ The task consists of two parts. alert( result ); // 8 ``` -- No brackets or complex expressions in this task. +- No parentheses or complex expressions in this task. - The numbers and the operator are delimited with exactly one space. - There may be error handling if you'd like to add it. diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md index a43715db8..6674c444f 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md @@ -45,7 +45,7 @@ for (let key in count) { } ``` -An example result (for V8, July 2017): +An example result (depends on JS engine): ```js 123: 250706 @@ -68,7 +68,13 @@ There are other good ways to do the task. For instance, there's a great algorith function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i - [array[i], array[j]] = [array[j], array[i]]; // swap elements + + // swap elements array[i] and array[j] + // we use "destructuring assignment" syntax to achieve that + // you'll find more details about that syntax in later chapters + // same can be written as: + // let t = array[i]; array[i] = array[j]; array[j] = t + [array[i], array[j]] = [array[j], array[i]]; } } ``` diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index 4261f52b1..8e5b4efdc 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -119,29 +119,28 @@ The method [arr.slice](mdn:js/Array/slice) is much simpler than similar-looking The syntax is: ```js -arr.slice(start, end) +arr.slice([start], [end]) ``` -It returns a new array containing all items from index `"start"` to `"end"` (not including `"end"`). Both `start` and `end` can be negative, in that case position from array end is assumed. +It returns a new array copying to it all items from index `start` to `end` (not including `end`). Both `start` and `end` can be negative, in that case position from array end is assumed. -It works like `str.slice`, but makes subarrays instead of substrings. +It's similar to a string method `str.slice`, but instead of substrings it makes subarrays. For instance: ```js run -let str = "test"; let arr = ["t", "e", "s", "t"]; -alert( str.slice(1, 3) ); // es -alert( arr.slice(1, 3) ); // e,s +alert( arr.slice(1, 3) ); // e,s (copy from 1 to 3) -alert( str.slice(-2) ); // st -alert( arr.slice(-2) ); // s,t +alert( arr.slice(-2) ); // s,t (copy from -2 till the end) ``` +We can also call it without arguments: `arr.slice()` creates a copy of `arr`. That's often used to obtain a copy for further transformations that should not affect the original array. + ### concat -The method [arr.concat](mdn:js/Array/concat) joins the array with other arrays and/or items. +The method [arr.concat](mdn:js/Array/concat) creates a new array that includes values from other arrays and additional items. The syntax is: @@ -153,24 +152,24 @@ It accepts any number of arguments -- either arrays or values. The result is a new array containing items from `arr`, then `arg1`, `arg2` etc. -If an argument is an array or has `Symbol.isConcatSpreadable` property, then all its elements are copied. Otherwise, the argument itself is copied. +If an argument `argN` is an array, then all its elements are copied. Otherwise, the argument itself is copied. For instance: ```js run let arr = [1, 2]; -// merge arr with [3,4] +// create an array from: arr and [3,4] alert( arr.concat([3, 4])); // 1,2,3,4 -// merge arr with [3,4] and [5,6] +// create an array from: arr and [3,4] and [5,6] alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6 -// merge arr with [3,4], then add values 5 and 6 +// create an array from: arr and [3,4], then add values 5 and 6 alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6 ``` -Normally, it only copies elements from arrays ("spreads" them). Other objects, even if they look like arrays, added as a whole: +Normally, it only copies elements from arrays. Other objects, even if they look like arrays, added as a whole: ```js run let arr = [1, 2]; @@ -184,7 +183,7 @@ alert( arr.concat(arrayLike) ); // 1,2,[object Object] //[1, 2, arrayLike] ``` -...But if an array-like object has `Symbol.isConcatSpreadable` property, then its elements are added instead: +...But if an array-like object has a special property `Symbol.isConcatSpreadable` property, the it's treated as array by `concat`: its elements are added instead: ```js run let arr = [1, 2]; @@ -232,7 +231,7 @@ The result of the function (if it returns any) is thrown away and ignored. ## Searching in array -These are methods to search for something in an array. +Now let's cover methods that search in an array. ### indexOf/lastIndexOf and includes @@ -280,7 +279,7 @@ let result = arr.find(function(item, index, array) { }); ``` -The function is called repetitively for each element of the array: +The function is called for elements of the array, one after another: - `item` is the element. - `index` is its index. @@ -304,7 +303,7 @@ alert(user.name); // John In real life arrays of objects is a common thing, so the `find` method is very useful. -Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. Other arguments of this function are rarely used. +Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. That's typical, other arguments of this function are rarely used. The [arr.findIndex](mdn:js/Array/findIndex) method is essentially the same, but it returns the index where the element was found instead of the element itself and `-1` is returned when nothing is found. @@ -314,12 +313,12 @@ The `find` method looks for a single (first) element that makes the function ret If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter). -The syntax is similar to `find`, but filter continues to iterate for all array elements even if `true` is already returned: +The syntax is similar to `find`, but `filter` returns an array of all matching elements: ```js let results = arr.filter(function(item, index, array) { - // if true item is pushed to results and iteration continues - // returns empty array for complete falsy scenario + // if true item is pushed to results and the iteration continues + // returns empty array if nothing found }); ``` @@ -340,23 +339,22 @@ alert(someUsers.length); // 2 ## Transform an array -This section is about the methods transforming or reordering the array. - +Let's move on to methods that transform and reorder an array. ### map The [arr.map](mdn:js/Array/map) method is one of the most useful and often used. +It calls the function for each element of the array and returns the array of results. + The syntax is: ```js let result = arr.map(function(item, index, array) { // returns the new value instead of item -}) +}); ``` -It calls the function for each element of the array and returns the array of results. - For instance, here we transform each element into its length: ```js run @@ -366,14 +364,16 @@ alert(lengths); // 5,7,6 ### sort(fn) -The method [arr.sort](mdn:js/Array/sort) sorts the array *in place*. +The call to [arr.sort()](mdn:js/Array/sort) sorts the array *in place*, changing its element order. + +It also returns the sorted array, but the returned value is usually ignored, as `arr` itself is modified. For instance: ```js run let arr = [ 1, 2, 15 ]; -// the method reorders the content of arr (and returns it) +// the method reorders the content of arr arr.sort(); alert( arr ); // *!*1, 15, 2*/!* @@ -385,20 +385,20 @@ The order became `1, 15, 2`. Incorrect. But why? **The items are sorted as strings by default.** -Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed `"2" > "15"`. +Literally, all elements are converted to strings for comparisons. For strings, lexicographic ordering is applied and indeed `"2" > "15"`. -To use our own sorting order, we need to supply a function of two arguments as the argument of `arr.sort()`. +To use our own sorting order, we need to supply a function as the argument of `arr.sort()`. -The function should work like this: +The function should compare two arbitrary values and return: ```js function compare(a, b) { - if (a > b) return 1; - if (a == b) return 0; - if (a < b) return -1; + if (a > b) return 1; // if the first value is greater than the second + if (a == b) return 0; // if values are equal + if (a < b) return -1; // if the first value is less than the second } ``` -For instance: +For instance, to sort as numbers: ```js run function compareNumeric(a, b) { @@ -418,9 +418,9 @@ alert(arr); // *!*1, 2, 15*/!* Now it works as intended. -Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or HTML elements or whatever. We have a set of *something*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order. +Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or objects or whatever. We have a set of *some items*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order. -The `arr.sort(fn)` method has a built-in implementation of sorting algorithm. We don't need to care how it exactly works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison. +The `arr.sort(fn)` method implements a generic sorting algorithm. We don't need to care how it internally works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison. By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them: @@ -430,7 +430,7 @@ By the way, if we ever want to know which elements are compared -- nothing preve }); ``` -The algorithm may compare an element multiple times in the process, but it tries to make as few comparisons as possible. +The algorithm may compare an element with multiple others in the process, but it tries to make as few comparisons as possible. ````smart header="A comparison function may return any number" @@ -454,7 +454,7 @@ Remember [arrow functions](info:function-expressions-arrows#arrow-functions)? We arr.sort( (a, b) => a - b ); ``` -This works exactly the same as the other, longer, version above. +This works exactly the same as the longer version above. ```` ### reverse @@ -508,14 +508,14 @@ alert( str.split('') ); // t,e,s,t ``` ```` -The call [arr.join(separator)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items glued by `separator` between them. +The call [arr.join(glue)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items joined by `glue` between them. For instance: ```js run let arr = ['Bilbo', 'Gandalf', 'Nazgul']; -let str = arr.join(';'); +let str = arr.join(';'); // glue the array into a string using ; alert( str ); // Bilbo;Gandalf;Nazgul ``` @@ -533,18 +533,21 @@ The syntax is: ```js let value = arr.reduce(function(previousValue, item, index, array) { // ... -}, initial); +}, [initial]); ``` -The function is applied to the elements. You may notice the familiar arguments, starting from the 2nd: +The function is applied to all array elements one after another and "carries on" its result to the next call. + +Arguments: +- `previousValue` -- is the result of the previous function call, equals `initial` the first time (if `initial` is provided). - `item` -- is the current array item. - `index` -- is its position. - `array` -- is the array. -So far, like `forEach/map`. But there's one more argument: +As function is applied, the result of the previous function call is passed to the next one as the first argument. -- `previousValue` -- is the result of the previous function call, `initial` for the first call. +Sounds complicated, but it's not if you think about the first argument as the "accumulator" that stores the combined result of all previous execution. And at the end it becomes the result of `reduce`. The easiest way to grasp that is by example. @@ -558,17 +561,17 @@ let result = arr.reduce((sum, current) => sum + current, 0); alert(result); // 15 ``` -Here we used the most common variant of `reduce` which uses only 2 arguments. +The function passed to `reduce` uses only 2 arguments, that's typically enough. Let's see the details of what's going on. -1. On the first run, `sum` is the initial value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the result is `1`. +1. On the first run, `sum` is the `initial` value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the function result is `1`. 2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return. 3. On the 3rd run, `sum = 3` and we add one more element to it, and so on... The calculation flow: -![](reduce.png) +![](reduce.svg) Or in the form of a table, where each row represents a function call on the next array element: @@ -580,8 +583,7 @@ Or in the form of a table, where each row represents a function call on the next |the fourth call|`6`|`4`|`10`| |the fifth call|`10`|`5`|`15`| - -As we can see, the result of the previous call becomes the first argument of the next one. +Here we can clearly see how the result of the previous call becomes the first argument of the next one. We also can omit the initial value: @@ -653,7 +655,7 @@ arr.map(func, thisArg); The value of `thisArg` parameter becomes `this` for `func`. -For instance, here we use an object method as a filter and `thisArg` comes in handy: +For instance, here we use an object method as a filter and `thisArg` helps with that: ```js run let user = { @@ -697,7 +699,7 @@ A cheat sheet of array methods: - `includes(value)` -- returns `true` if the array has `value`, otherwise `false`. - `find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`. - `findIndex` is like `find`, but returns the index instead of a value. - + - To iterate over elements: - `forEach(func)` -- calls `func` for every element, does not return anything. @@ -725,7 +727,7 @@ These methods are the most used ones, they cover 99% of use cases. But there are For the full list, see the [manual](mdn:js/Array). -From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier than it seems. +From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier. Look through the cheat sheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods. diff --git a/1-js/05-data-types/05-array-methods/reduce.png b/1-js/05-data-types/05-array-methods/reduce.png deleted file mode 100644 index 7566c4d84..000000000 Binary files a/1-js/05-data-types/05-array-methods/reduce.png and /dev/null differ diff --git a/1-js/05-data-types/05-array-methods/reduce.svg b/1-js/05-data-types/05-array-methods/reduce.svg new file mode 100644 index 000000000..47797bf7c --- /dev/null +++ b/1-js/05-data-types/05-array-methods/reduce.svg @@ -0,0 +1 @@ +1sum 0 current 12sum 0+1 current 23sum 0+1+2 current 34sum 0+1+2+3 current 45sum 0+1+2+3+4 current 50+1+2+3+4+5 = 15 \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/reduce@2x.png b/1-js/05-data-types/05-array-methods/reduce@2x.png deleted file mode 100644 index 7c9fd6692..000000000 Binary files a/1-js/05-data-types/05-array-methods/reduce@2x.png and /dev/null differ diff --git a/1-js/05-data-types/06-iterable/article.md b/1-js/05-data-types/06-iterable/article.md index 474d0463d..80f067ca8 100644 --- a/1-js/05-data-types/06-iterable/article.md +++ b/1-js/05-data-types/06-iterable/article.md @@ -3,9 +3,9 @@ *Iterable* objects is a generalization of arrays. That's a concept that allows to make any object useable in a `for..of` loop. -Of course, Arrays are iterable. But there are many other built-in objects, that are iterable as well. For instance, Strings are iterable also. As we'll see, many built-in operators and methods rely on them. +Of course, Arrays are iterable. But there are many other built-in objects, that are iterable as well. For instance, strings are also iterable. -If an object represents a collection (list, set) of something, then `for..of` is a great syntax to loop over it, so let's see how to make it work. +If an object isn't technically an array, but represents a collection (list, set) of something, then `for..of` is a great syntax to loop over it, so let's see how to make it work. ## Symbol.iterator @@ -31,9 +31,9 @@ To make the `range` iterable (and thus let `for..of` work) we need to add a meth 1. When `for..of` starts, it calls that method once (or errors if not found). The method must return an *iterator* -- an object with the method `next`. 2. Onward, `for..of` works *only with that returned object*. 3. When `for..of` wants the next value, it calls `next()` on that object. -4. The result of `next()` must have the form `{done: Boolean, value: any}`, where `done=true` means that the iteration is finished, otherwise `value` must be the new value. +4. The result of `next()` must have the form `{done: Boolean, value: any}`, where `done=true` means that the iteration is finished, otherwise `value` is the next value. -Here's the full implementation for `range`: +Here's the full implementation for `range` with remarks: ```js run let range = { @@ -68,10 +68,10 @@ for (let num of range) { } ``` -Please note the core feature of iterables: an important separation of concerns: +Please note the core feature of iterables: separation of concerns. - The `range` itself does not have the `next()` method. -- Instead, another object, a so-called "iterator" is created by the call to `range[Symbol.iterator]()`, and it handles the whole iteration. +- Instead, another object, a so-called "iterator" is created by the call to `range[Symbol.iterator]()`, and its `next()` generates values for the iteration. So, the iterator object is separate from the object it iterates over. @@ -140,9 +140,7 @@ for (let char of str) { ## Calling an iterator explicitly -Normally, internals of iterables are hidden from the external code. There's a `for..of` loop, that works, that's all it needs to know. - -But to understand things a little bit deeper let's see how to create an iterator explicitly. +For deeper understanding let's see how to use an iterator explicitly. We'll iterate over a string in exactlly the same way as `for..of`, but with direct calls. This code creates a string iterator and gets values from it "manually": @@ -283,7 +281,7 @@ let str = '𝒳😂𩷶'; alert( slice(str, 1, 3) ); // 😂𩷶 -// native method does not support surrogate pairs +// the native method does not support surrogate pairs alert( str.slice(1, 3) ); // garbage (two pieces from different surrogate pairs) ``` diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/article.md b/1-js/05-data-types/07-map-set-weakmap-weakset/article.md deleted file mode 100644 index 47658833f..000000000 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/article.md +++ /dev/null @@ -1,475 +0,0 @@ - -# Map, Set, WeakMap and WeakSet - -Now we've learned about the following complex data structures: - -- Objects for storing keyed collections. -- Arrays for storing ordered collections. - -But that's not enough for real life. That's why `Map` and `Set` also exist. - -## Map - -[Map](mdn:js/Map) is a collection of keyed data items, just like an `Object`. But the main difference is that `Map` allows keys of any type. - -The main methods are: - -- `new Map()` -- creates the map. -- `map.set(key, value)` -- stores the value by the key. -- `map.get(key)` -- returns the value by the key, `undefined` if `key` doesn't exist in map. -- `map.has(key)` -- returns `true` if the `key` exists, `false` otherwise. -- `map.delete(key)` -- removes the value by the key. -- `map.clear()` -- clears the map -- `map.size` -- returns the current element count. - -For instance: - -```js run -let map = new Map(); - -map.set('1', 'str1'); // a string key -map.set(1, 'num1'); // a numeric key -map.set(true, 'bool1'); // a boolean key - -// remember the regular Object? it would convert keys to string -// Map keeps the type, so these two are different: -alert( map.get(1) ); // 'num1' -alert( map.get('1') ); // 'str1' - -alert( map.size ); // 3 -``` - -As we can see, unlike objects, keys are not converted to strings. Any type of key is possible. - -**Map can also use objects as keys.** - -For instance: -```js run -let john = { name: "John" }; - -// for every user, let's store their visits count -let visitsCountMap = new Map(); - -// john is the key for the map -visitsCountMap.set(john, 123); - -alert( visitsCountMap.get(john) ); // 123 -``` - -Using objects as keys is one of most notable and important `Map` features. For string keys, `Object` can be fine, but it would be difficult to replace the `Map` with a regular `Object` in the example above. - -Let's try: - -```js run -let john = { name: "John" }; - -let visitsCountObj = {}; // try to use an object - -visitsCountObj[john] = 123; // try to use john object as the key - -*!* -// That's what got written! -alert( visitsCountObj["[object Object]"] ); // 123 -*/!* -``` - -As `john` is an object, it got converted to the key string `"[object Object]"`. All objects without a special conversion handling are converted to such string, so they'll all mess up. - -In the old times, before `Map` existed, people used to add unique identifiers to objects for that: - -```js run -// we add the id field -let john = { name: "John", *!*id: 1*/!* }; - -let visitsCounts = {}; - -// now store the value by id -visitsCounts[john.id] = 123; - -alert( visitsCounts[john.id] ); // 123 -``` - -...But `Map` is much more elegant. - - -```smart header="How `Map` compares keys" -To test values for equivalence, `Map` uses the algorithm [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero). It is roughly the same as strict equality `===`, but the difference is that `NaN` is considered equal to `NaN`. So `NaN` can be used as the key as well. - -This algorithm can't be changed or customized. -``` - - -````smart header="Chaining" - -Every `map.set` call returns the map itself, so we can "chain" the calls: - -```js -map.set('1', 'str1') - .set(1, 'num1') - .set(true, 'bool1'); -``` -```` - -## Map from Object - -When a `Map` is created, we can pass an array (or another iterable) with key-value pairs, like this: - -```js -// array of [key, value] pairs -let map = new Map([ - ['1', 'str1'], - [1, 'num1'], - [true, 'bool1'] -]); -``` - -There is a built-in method [Object.entries(obj)](mdn:js/Object/entries) that returns an array of key/value pairs for an object exactly in that format. - -So we can initialize a map from an object like this: - -```js -let map = new Map(Object.entries({ - name: "John", - age: 30 -})); -``` - -Here, `Object.entries` returns the array of key/value pairs: `[ ["name","John"], ["age", 30] ]`. That's what `Map` needs. - -## Iteration over Map - -For looping over a `map`, there are 3 methods: - -- `map.keys()` -- returns an iterable for keys, -- `map.values()` -- returns an iterable for values, -- `map.entries()` -- returns an iterable for entries `[key, value]`, it's used by default in `for..of`. - -For instance: - -```js run -let recipeMap = new Map([ - ['cucumber', 500], - ['tomatoes', 350], - ['onion', 50] -]); - -// iterate over keys (vegetables) -for (let vegetable of recipeMap.keys()) { - alert(vegetable); // cucumber, tomatoes, onion -} - -// iterate over values (amounts) -for (let amount of recipeMap.values()) { - alert(amount); // 500, 350, 50 -} - -// iterate over [key, value] entries -for (let entry of recipeMap) { // the same as of recipeMap.entries() - alert(entry); // cucumber,500 (and so on) -} -``` - -```smart header="The insertion order is used" -The iteration goes in the same order as the values were inserted. `Map` preserves this order, unlike a regular `Object`. -``` - -Besides that, `Map` has a built-in `forEach` method, similar to `Array`: - -```js -// runs the function for each (key, value) pair -recipeMap.forEach( (value, key, map) => { - alert(`${key}: ${value}`); // cucumber: 500 etc -}); -``` - - -## Set - -A `Set` is a collection of values, where each value may occur only once. - -Its main methods are: - -- `new Set(iterable)` -- creates the set, and if an `iterable` object is provided (usually an array), copies values from it into the set. -- `set.add(value)` -- adds a value, returns the set itself. -- `set.delete(value)` -- removes the value, returns `true` if `value` existed at the moment of the call, otherwise `false`. -- `set.has(value)` -- returns `true` if the value exists in the set, otherwise `false`. -- `set.clear()` -- removes everything from the set. -- `set.size` -- is the elements count. - -For example, we have visitors coming, and we'd like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be "counted" only once. - -`Set` is just the right thing for that: - -```js run -let set = new Set(); - -let john = { name: "John" }; -let pete = { name: "Pete" }; -let mary = { name: "Mary" }; - -// visits, some users come multiple times -set.add(john); -set.add(pete); -set.add(mary); -set.add(john); -set.add(mary); - -// set keeps only unique values -alert( set.size ); // 3 - -for (let user of set) { - alert(user.name); // John (then Pete and Mary) -} -``` - -The alternative to `Set` could be an array of users, and the code to check for duplicates on every insertion using [arr.find](mdn:js/Array/find). But the performance would be much worse, because this method walks through the whole array checking every element. `Set` is much better optimized internally for uniqueness checks. - -## Iteration over Set - -We can loop over a set either with `for..of` or using `forEach`: - -```js run -let set = new Set(["oranges", "apples", "bananas"]); - -for (let value of set) alert(value); - -// the same with forEach: -set.forEach((value, valueAgain, set) => { - alert(value); -}); -``` - -Note the funny thing. The callback function passed in `forEach` has 3 arguments: a value, then *again a value*, and then the target object. Indeed, the same value appears in the arguments twice. - -That's for compatibility with `Map` where the callback passed `forEach` has three arguments. Looks a bit strange, for sure. But may help to replace `Map` with `Set` in certain cases with ease, and vice versa. - -The same methods `Map` has for iterators are also supported: - -- `set.keys()` -- returns an iterable object for values, -- `set.values()` -- same as `set.keys`, for compatibility with `Map`, -- `set.entries()` -- returns an iterable object for entries `[value, value]`, exists for compatibility with `Map`. - -## WeakMap and WeakSet - -`WeakSet` is a special kind of `Set` that does not prevent JavaScript from removing its items from memory. `WeakMap` is the same thing for `Map`. - -As we know from the chapter , JavaScript engine stores a value in memory while it is reachable (and can potentially be used). - -For instance: -```js -let john = { name: "John" }; - -// the object can be accessed, john is the reference to it - -// overwrite the reference -john = null; - -*!* -// the object will be removed from memory -*/!* -``` - -Usually, properties of an object or elements of an array or another data structure are considered reachable and kept in memory while that data structure is in memory. - -For instance, if we put an object into an array, then while the array is alive, the object will be alive as well, even if there are no other references to it. - -Like this: - -```js -let john = { name: "John" }; - -let array = [ john ]; - -john = null; // overwrite the reference - -*!* -// john is stored inside the array, so it won't be garbage-collected -// we can get it as array[0] -*/!* -``` - -Or, if we use an object as the key in a regular `Map`, then while the `Map` exists, that object exists as well. It occupies memory and may not be garbage collected. - -For instance: - -```js -let john = { name: "John" }; - -let map = new Map(); -map.set(john, "..."); - -john = null; // overwrite the reference - -*!* -// john is stored inside the map, -// we can get it by using map.keys() -*/!* -``` - -`WeakMap/WeakSet` are fundamentally different in this aspect. They do not prevent garbage-collection of key objects. - -Let's explain it starting with `WeakMap`. - -The first difference from `Map` is that `WeakMap` keys must be objects, not primitive values: - -```js run -let weakMap = new WeakMap(); - -let obj = {}; - -weakMap.set(obj, "ok"); // works fine (object key) - -*!* -// can't use a string as the key -weakMap.set("test", "Whoops"); // Error, because "test" is not an object -*/!* -``` - -Now, if we use an object as the key in it, and there are no other references to that object -- it will be removed from memory (and from the map) automatically. - -```js -let john = { name: "John" }; - -let weakMap = new WeakMap(); -weakMap.set(john, "..."); - -john = null; // overwrite the reference - -// john is removed from memory! -``` - -Compare it with the regular `Map` example above. Now if `john` only exists as the key of `WeakMap` -- it is to be automatically deleted. - -`WeakMap` does not support iteration and methods `keys()`, `values()`, `entries()`, so there's no way to get all keys or values from it. - -`WeakMap` has only the following methods: - -- `weakMap.get(key)` -- `weakMap.set(key, value)` -- `weakMap.delete(key)` -- `weakMap.has(key)` - -Why such a limitation? That's for technical reasons. If an object has lost all other references (like `john` in the code above), then it is to be garbage-collected automatically. But technically it's not exactly specified *when the cleanup happens*. - -The JavaScript engine decides that. It may choose to perform the memory cleanup immediately or to wait and do the cleaning later when more deletions happen. So, technically the current element count of a `WeakMap` is not known. The engine may have cleaned it up or not, or did it partially. For that reason, methods that access `WeakMap` as a whole are not supported. - -Now where do we need such thing? - -The idea of `WeakMap` is that we can store something for an object that should exist only while the object exists. But we do not force the object to live by the mere fact that we store something for it. - -```js -weakMap.set(john, "secret documents"); -// if john dies, secret documents will be destroyed automatically -``` - -That's useful for situations when we have a main storage for the objects somewhere and need to keep additional information, that is only relevant while the object lives. - -Let's look at an example. - -For instance, we have code that keeps a visit count for each user. The information is stored in a map: a user is the key and the visit count is the value. When a user leaves, we don't want to store their visit count anymore. - -One way would be to keep track of users, and when they leave -- clean up the map manually: - -```js run -let john = { name: "John" }; - -// map: user => visits count -let visitsCountMap = new Map(); - -// john is the key for the map -visitsCountMap.set(john, 123); - -// now john leaves us, we don't need him anymore -john = null; - -*!* -// but it's still in the map, we need to clean it! -*/!* -alert( visitsCountMap.size ); // 1 -// and john is also in the memory, because Map uses it as the key -``` - -Another way would be to use `WeakMap`: - -```js -let john = { name: "John" }; - -let visitsCountMap = new WeakMap(); - -visitsCountMap.set(john, 123); - -// now john leaves us, we don't need him anymore -john = null; - -// there are no references except WeakMap, -// so the object is removed both from the memory and from visitsCountMap automatically -``` - -With a regular `Map`, cleaning up after a user has left becomes a tedious task: we not only need to remove the user from its main storage (be it a variable or an array), but also need to clean up the additional stores like `visitsCountMap`. And it can become cumbersome in more complex cases when users are managed in one place of the code and the additional structure is in another place and is getting no information about removals. - -```summary -`WeakMap` can make things simpler, because it is cleaned up automatically. The information in it like visits count in the example above lives only while the key object exists. -``` - -`WeakSet` behaves similarly: - -- It is analogous to `Set`, but we may only add objects to `WeakSet` (not primitives). -- An object exists in the set while it is reachable from somewhere else. -- Like `Set`, it supports `add`, `has` and `delete`, but not `size`, `keys()` and no iterations. - -For instance, we can use it to keep track of whether a message is read: - -```js -let messages = [ - {text: "Hello", from: "John"}, - {text: "How goes?", from: "John"}, - {text: "See you soon", from: "Alice"} -]; - -// fill it with array elements (3 items) -let unreadSet = new WeakSet(messages); - -// use unreadSet to see whether a message is unread -alert(unreadSet.has(messages[1])); // true - -// remove it from the set after reading -unreadSet.delete(messages[1]); // true - -// and when we shift our messages history, the set is cleaned up automatically -messages.shift(); - -*!* -// no need to clean unreadSet, it now has 2 items -*/!* -// (though technically we don't know for sure when the JS engine clears it) -``` - -The most notable limitation of `WeakMap` and `WeakSet` is the absence of iterations, and inability to get all current content. That may appear inconvenient, but does not prevent `WeakMap/WeakSet` from doing their main job -- be an "additional" storage of data for objects which are stored/managed at another place. - -## Summary - -Regular collections: -- `Map` -- is a collection of keyed values. - - The differences from a regular `Object`: - - - Any keys, objects can be keys. - - Iterates in the insertion order. - - Additional convenient methods, the `size` property. - -- `Set` -- is a collection of unique values. - - - Unlike an array, does not allow to reorder elements. - - Keeps the insertion order. - -Collections that allow garbage-collection: - -- `WeakMap` -- a variant of `Map` that allows only objects as keys and removes them once they become inaccessible by other means. - - - It does not support operations on the structure as a whole: no `size`, no `clear()`, no iterations. - -- `WeakSet` -- is a variant of `Set` that only stores objects and removes them once they become inaccessible by other means. - - - Also does not support `size/clear()` and iterations. - -`WeakMap` and `WeakSet` are used as "secondary" data structures in addition to the "main" object storage. Once the object is removed from the main storage, if it is only found in the `WeakMap/WeakSet`, it will be cleaned up automatically. diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/_js.view/solution.js b/1-js/05-data-types/07-map-set/01-array-unique-map/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/_js.view/solution.js rename to 1-js/05-data-types/07-map-set/01-array-unique-map/_js.view/solution.js diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/_js.view/test.js b/1-js/05-data-types/07-map-set/01-array-unique-map/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/_js.view/test.js rename to 1-js/05-data-types/07-map-set/01-array-unique-map/_js.view/test.js diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/solution.md b/1-js/05-data-types/07-map-set/01-array-unique-map/solution.md similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/solution.md rename to 1-js/05-data-types/07-map-set/01-array-unique-map/solution.md diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/task.md b/1-js/05-data-types/07-map-set/01-array-unique-map/task.md similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/01-array-unique-map/task.md rename to 1-js/05-data-types/07-map-set/01-array-unique-map/task.md diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/_js.view/solution.js b/1-js/05-data-types/07-map-set/02-filter-anagrams/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/_js.view/solution.js rename to 1-js/05-data-types/07-map-set/02-filter-anagrams/_js.view/solution.js diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/_js.view/test.js b/1-js/05-data-types/07-map-set/02-filter-anagrams/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/_js.view/test.js rename to 1-js/05-data-types/07-map-set/02-filter-anagrams/_js.view/test.js diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/solution.md b/1-js/05-data-types/07-map-set/02-filter-anagrams/solution.md similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/solution.md rename to 1-js/05-data-types/07-map-set/02-filter-anagrams/solution.md diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/task.md b/1-js/05-data-types/07-map-set/02-filter-anagrams/task.md similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/02-filter-anagrams/task.md rename to 1-js/05-data-types/07-map-set/02-filter-anagrams/task.md diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/03-iterable-keys/solution.md b/1-js/05-data-types/07-map-set/03-iterable-keys/solution.md similarity index 100% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/03-iterable-keys/solution.md rename to 1-js/05-data-types/07-map-set/03-iterable-keys/solution.md diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/03-iterable-keys/task.md b/1-js/05-data-types/07-map-set/03-iterable-keys/task.md similarity index 63% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/03-iterable-keys/task.md rename to 1-js/05-data-types/07-map-set/03-iterable-keys/task.md index b1ccbd0ac..25c74bfc2 100644 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/03-iterable-keys/task.md +++ b/1-js/05-data-types/07-map-set/03-iterable-keys/task.md @@ -4,9 +4,9 @@ importance: 5 # Iterable keys -We want to get an array of `map.keys()` and go on working with it (apart from the map itself). +We'd like to get an array of `map.keys()` in a variable and then do apply array-specific methods to it, e.g. `.push`. -But there's a problem: +But that doesn't work: ```js run let map = new Map(); diff --git a/1-js/05-data-types/07-map-set/article.md b/1-js/05-data-types/07-map-set/article.md new file mode 100644 index 000000000..c4d7c21a4 --- /dev/null +++ b/1-js/05-data-types/07-map-set/article.md @@ -0,0 +1,324 @@ + +# Map and Set + +Now we've learned about the following complex data structures: + +- Objects for storing keyed collections. +- Arrays for storing ordered collections. + +But that's not enough for real life. That's why `Map` and `Set` also exist. + +## Map + +[Map](mdn:js/Map) is a collection of keyed data items, just like an `Object`. But the main difference is that `Map` allows keys of any type. + +Methods and properties are: + +- `new Map()` -- creates the map. +- `map.set(key, value)` -- stores the value by the key. +- `map.get(key)` -- returns the value by the key, `undefined` if `key` doesn't exist in map. +- `map.has(key)` -- returns `true` if the `key` exists, `false` otherwise. +- `map.delete(key)` -- removes the value by the key. +- `map.clear()` -- removes everything from the map. +- `map.size` -- returns the current element count. + +For instance: + +```js run +let map = new Map(); + +map.set('1', 'str1'); // a string key +map.set(1, 'num1'); // a numeric key +map.set(true, 'bool1'); // a boolean key + +// remember the regular Object? it would convert keys to string +// Map keeps the type, so these two are different: +alert( map.get(1) ); // 'num1' +alert( map.get('1') ); // 'str1' + +alert( map.size ); // 3 +``` + +As we can see, unlike objects, keys are not converted to strings. Any type of key is possible. + +**Map can also use objects as keys.** + +For instance: + +```js run +let john = { name: "John" }; + +// for every user, let's store their visits count +let visitsCountMap = new Map(); + +// john is the key for the map +visitsCountMap.set(john, 123); + +alert( visitsCountMap.get(john) ); // 123 +``` + +Using objects as keys is one of most notable and important `Map` features. For string keys, `Object` can be fine, but not for object keys. + +Let's try: + +```js run +let john = { name: "John" }; + +let visitsCountObj = {}; // try to use an object + +visitsCountObj[john] = 123; // try to use john object as the key + +*!* +// That's what got written! +alert( visitsCountObj["[object Object]"] ); // 123 +*/!* +``` + +As `visitsCountObj` is an object, it converts all keys, such as `john` to strings, so we've got the string key `"[object Object]"`. Definitely not what we want. + +```smart header="How `Map` compares keys" +To test keys for equivalence, `Map` uses the algorithm [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero). It is roughly the same as strict equality `===`, but the difference is that `NaN` is considered equal to `NaN`. So `NaN` can be used as the key as well. + +This algorithm can't be changed or customized. +``` + +````smart header="Chaining" +Every `map.set` call returns the map itself, so we can "chain" the calls: + +```js +map.set('1', 'str1') + .set(1, 'num1') + .set(true, 'bool1'); +``` +```` + + +## Iteration over Map + +For looping over a `map`, there are 3 methods: + +- `map.keys()` -- returns an iterable for keys, +- `map.values()` -- returns an iterable for values, +- `map.entries()` -- returns an iterable for entries `[key, value]`, it's used by default in `for..of`. + +For instance: + +```js run +let recipeMap = new Map([ + ['cucumber', 500], + ['tomatoes', 350], + ['onion', 50] +]); + +// iterate over keys (vegetables) +for (let vegetable of recipeMap.keys()) { + alert(vegetable); // cucumber, tomatoes, onion +} + +// iterate over values (amounts) +for (let amount of recipeMap.values()) { + alert(amount); // 500, 350, 50 +} + +// iterate over [key, value] entries +for (let entry of recipeMap) { // the same as of recipeMap.entries() + alert(entry); // cucumber,500 (and so on) +} +``` + +```smart header="The insertion order is used" +The iteration goes in the same order as the values were inserted. `Map` preserves this order, unlike a regular `Object`. +``` + +Besides that, `Map` has a built-in `forEach` method, similar to `Array`: + +```js +// runs the function for each (key, value) pair +recipeMap.forEach( (value, key, map) => { + alert(`${key}: ${value}`); // cucumber: 500 etc +}); +``` + +## Object.entries: Map from Object + +When a `Map` is created, we can pass an array (or another iterable) with key/value pairs for initialization, like this: + +```js run +// array of [key, value] pairs +let map = new Map([ + ['1', 'str1'], + [1, 'num1'], + [true, 'bool1'] +]); + +alert( map.get('1') ); // str1 +``` + +If we have a plain object, and we'd like to create a `Map` from it, then we can use built-in method [Object.entries(obj)](mdn:js/Object/entries) that returns an array of key/value pairs for an object exactly in that format. + +So we can create a map from an object like this: + +```js run +let obj = { + name: "John", + age: 30 +}; + +*!* +let map = new Map(Object.entries(obj)); +*/!* + +alert( map.get('name') ); // John +``` + +Here, `Object.entries` returns the array of key/value pairs: `[ ["name","John"], ["age", 30] ]`. That's what `Map` needs. + + +## Object.fromEntries: Object from Map + +We've just seen how to create `Map` from a plain object with `Object.entries(obj)`. + +There's `Object.fromEntries` method that does the reverse: given an array of `[key, value]` pairs, it creates an object from them: + +```js run +let prices = Object.fromEntries([ + ['banana', 1], + ['orange', 2], + ['meat', 4] +]); + +// now prices = { banana: 1, orange: 2, meat: 4 } + +alert(prices.orange); // 2 +``` + +We can use `Object.fromEntries` to get an plain object from `Map`. + +E.g. we store the data in a `Map`, but we need to pass it to a 3rd-party code that expects a plain object. + +Here we go: + +```js run +let map = new Map(); +map.set('banana', 1); +map.set('orange', 2); +map.set('meat', 4); + +*!* +let obj = Object.fromEntries(map.entries()); // make a plain object (*) +*/!* + +// done! +// obj = { banana: 1, orange: 2, meat: 4 } + +alert(obj.orange); // 2 +``` + +A call to `map.entries()` returns an array of key/value pairs, exactly in the right format for `Object.fromEntries`. + +We could also make line `(*)` shorter: +```js +let obj = Object.fromEntries(map); // omit .entries() +``` + +That's the same, because `Object.fromEntries` expects an iterable object as the argument. Not necessarily an array. And the standard iteration for `map` returns same key/value pairs as `map.entries()`. So we get a plain object with same key/values as the `map`. + +## Set + +A `Set` is a special type collection - "set of values" (without keys), where each value may occur only once. + +Its main methods are: + +- `new Set(iterable)` -- creates the set, and if an `iterable` object is provided (usually an array), copies values from it into the set. +- `set.add(value)` -- adds a value, returns the set itself. +- `set.delete(value)` -- removes the value, returns `true` if `value` existed at the moment of the call, otherwise `false`. +- `set.has(value)` -- returns `true` if the value exists in the set, otherwise `false`. +- `set.clear()` -- removes everything from the set. +- `set.size` -- is the elements count. + +The main feature is that repeated calls of `set.add(value)` with the same value don't do anything. That's the reason why each value appears in a `Set` only once. + +For example, we have visitors coming, and we'd like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be "counted" only once. + +`Set` is just the right thing for that: + +```js run +let set = new Set(); + +let john = { name: "John" }; +let pete = { name: "Pete" }; +let mary = { name: "Mary" }; + +// visits, some users come multiple times +set.add(john); +set.add(pete); +set.add(mary); +set.add(john); +set.add(mary); + +// set keeps only unique values +alert( set.size ); // 3 + +for (let user of set) { + alert(user.name); // John (then Pete and Mary) +} +``` + +The alternative to `Set` could be an array of users, and the code to check for duplicates on every insertion using [arr.find](mdn:js/Array/find). But the performance would be much worse, because this method walks through the whole array checking every element. `Set` is much better optimized internally for uniqueness checks. + +## Iteration over Set + +We can loop over a set either with `for..of` or using `forEach`: + +```js run +let set = new Set(["oranges", "apples", "bananas"]); + +for (let value of set) alert(value); + +// the same with forEach: +set.forEach((value, valueAgain, set) => { + alert(value); +}); +``` + +Note the funny thing. The callback function passed in `forEach` has 3 arguments: a `value`, then *the same value* `valueAgain`, and then the target object. Indeed, the same value appears in the arguments twice. + +That's for compatibility with `Map` where the callback passed `forEach` has three arguments. Looks a bit strange, for sure. But may help to replace `Map` with `Set` in certain cases with ease, and vice versa. + +The same methods `Map` has for iterators are also supported: + +- `set.keys()` -- returns an iterable object for values, +- `set.values()` -- same as `set.keys()`, for compatibility with `Map`, +- `set.entries()` -- returns an iterable object for entries `[value, value]`, exists for compatibility with `Map`. + +## Summary + +`Map` -- is a collection of keyed values. + +Methods and properties: + +- `new Map([iterable])` -- creates the map, with optional `iterable` (e.g. array) of `[key,value]` pairs for initialization. +- `map.set(key, value)` -- stores the value by the key. +- `map.get(key)` -- returns the value by the key, `undefined` if `key` doesn't exist in map. +- `map.has(key)` -- returns `true` if the `key` exists, `false` otherwise. +- `map.delete(key)` -- removes the value by the key. +- `map.clear()` -- removes everything from the map. +- `map.size` -- returns the current element count. + +The differences from a regular `Object`: + +- Any keys, objects can be keys. +- Additional convenient methods, the `size` property. + +`Set` -- is a collection of unique values. + +Methods and properties: + +- `new Set([iterable])` -- creates the set, with optional `iterable` (e.g. array) of values for initialization. +- `set.add(value)` -- adds a value (does nothing if `value` exists), returns the set itself. +- `set.delete(value)` -- removes the value, returns `true` if `value` existed at the moment of the call, otherwise `false`. +- `set.has(value)` -- returns `true` if the value exists in the set, otherwise `false`. +- `set.clear()` -- removes everything from the set. +- `set.size` -- is the elements count. + +Iteration over `Map` and `Set` is always in the insertion order, so we can't say that these collections are unordered, but we can't reorder elements or directly get an element by its number. diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/solution.md b/1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solution.md similarity index 52% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/solution.md rename to 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solution.md index ce56f593a..f0c6ed45f 100644 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/solution.md +++ b/1-js/05-data-types/08-weakmap-weakset/01-recipients-read/solution.md @@ -1,10 +1,10 @@ -The sane choice here is a `WeakSet`: +Let's store read messages in `WeakSet`: ```js let messages = [ - {text: "Hello", from: "John"}, - {text: "How goes?", from: "John"}, - {text: "See you soon", from: "Alice"} + {text: "Hello", from: "John"}, + {text: "How goes?", from: "John"}, + {text: "See you soon", from: "Alice"} ]; let readMessages = new WeakSet(); @@ -27,9 +27,9 @@ messages.shift(); The `WeakSet` allows to store a set of messages and easily check for the existance of a message in it. -It cleans up itself automatically. The tradeoff is that we can't iterate over it. We can't get "all read messages" directly. But we can do it by iterating over all messages and filtering those that are in the set. +It cleans up itself automatically. The tradeoff is that we can't iterate over it, can't get "all read messages" from it directly. But we can do it by iterating over all messages and filtering those that are in the set. -P.S. Adding a property of our own to each message may be dangerous if messages are managed by someone else's code, but we can make it a symbol to evade conflicts. +Another, different solution could be to add a property like `message.isRead=true` to a message after it's read. As messages objects are managed by another code, that's generally discouraged, but we can use a symbolic property to avoid conflicts. Like this: ```js @@ -38,4 +38,6 @@ let isRead = Symbol("isRead"); messages[0][isRead] = true; ``` -Now even if someone else's code uses `for..in` loop for message properties, our secret flag won't appear. +Now third-party code probably won't see our extra property. + +Although symbols allow to lower the probability of problems, using `WeakSet` is better from the architectural point of view. diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/task.md b/1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md similarity index 68% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/task.md rename to 1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md index 7ec1faf16..c3d3bbc0a 100644 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/04-recipients-read/task.md +++ b/1-js/05-data-types/08-weakmap-weakset/01-recipients-read/task.md @@ -8,9 +8,9 @@ There's an array of messages: ```js let messages = [ - {text: "Hello", from: "John"}, - {text: "How goes?", from: "John"}, - {text: "See you soon", from: "Alice"} + {text: "Hello", from: "John"}, + {text: "How goes?", from: "John"}, + {text: "See you soon", from: "Alice"} ]; ``` @@ -20,4 +20,4 @@ Now, which data structure you could use to store information whether the message P.S. When a message is removed from `messages`, it should disappear from your structure as well. -P.P.S. We shouldn't modify message objects directly. If they are managed by someone else's code, then adding extra properties to them may have bad consequences. +P.P.S. We shouldn't modify message objects, add our properties to them. As they are managed by someone else's code, that may lead to bad consequences. diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/solution.md b/1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/solution.md similarity index 61% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/solution.md rename to 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/solution.md index 7f387b4da..2af0547c1 100644 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/solution.md +++ b/1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/solution.md @@ -3,9 +3,9 @@ To store a date, we can use `WeakMap`: ```js let messages = [ - {text: "Hello", from: "John"}, - {text: "How goes?", from: "John"}, - {text: "See you soon", from: "Alice"} + {text: "Hello", from: "John"}, + {text: "How goes?", from: "John"}, + {text: "See you soon", from: "Alice"} ]; let readMap = new WeakMap(); diff --git a/1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/task.md b/1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/task.md similarity index 54% rename from 1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/task.md rename to 1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/task.md index 22b51a382..8e341c184 100644 --- a/1-js/05-data-types/07-map-set-weakmap-weakset/05-recipients-when-read/task.md +++ b/1-js/05-data-types/08-weakmap-weakset/02-recipients-when-read/task.md @@ -8,12 +8,14 @@ There's an array of messages as in the [previous task](info:task/recipients-read ```js let messages = [ - {text: "Hello", from: "John"}, - {text: "How goes?", from: "John"}, - {text: "See you soon", from: "Alice"} + {text: "Hello", from: "John"}, + {text: "How goes?", from: "John"}, + {text: "See you soon", from: "Alice"} ]; ``` The question now is: which data structure you'd suggest to store the information: "when the message was read?". -In the previous task we only needed to store the "yes/no" fact. Now we need to store the date and it, once again, should disappear if the message is gone. +In the previous task we only needed to store the "yes/no" fact. Now we need to store the date, and it should only remain in memory until the message is garbage collected. + +P.S. Dates can be stored as objects of built-in `Date` class, that we'll cover later. diff --git a/1-js/05-data-types/08-weakmap-weakset/article.md b/1-js/05-data-types/08-weakmap-weakset/article.md new file mode 100644 index 000000000..01b0eb985 --- /dev/null +++ b/1-js/05-data-types/08-weakmap-weakset/article.md @@ -0,0 +1,289 @@ +# WeakMap and WeakSet + +As we know from the chapter , JavaScript engine stores a value in memory while it is reachable (and can potentially be used). + +For instance: +```js +let john = { name: "John" }; + +// the object can be accessed, john is the reference to it + +// overwrite the reference +john = null; + +*!* +// the object will be removed from memory +*/!* +``` + +Usually, properties of an object or elements of an array or another data structure are considered reachable and kept in memory while that data structure is in memory. + +For instance, if we put an object into an array, then while the array is alive, the object will be alive as well, even if there are no other references to it. + +Like this: + +```js +let john = { name: "John" }; + +let array = [ john ]; + +john = null; // overwrite the reference + +*!* +// john is stored inside the array, so it won't be garbage-collected +// we can get it as array[0] +*/!* +``` + +Similar to that, if we use an object as the key in a regular `Map`, then while the `Map` exists, that object exists as well. It occupies memory and may not be garbage collected. + +For instance: + +```js +let john = { name: "John" }; + +let map = new Map(); +map.set(john, "..."); + +john = null; // overwrite the reference + +*!* +// john is stored inside the map, +// we can get it by using map.keys() +*/!* +``` + +`WeakMap` is fundamentally different in this aspect. It doesn't prevent garbage-collection of key objects. + +Let's see what it means on examples. + +## WeakMap + +The first difference from `Map` is that `WeakMap` keys must be objects, not primitive values: + +```js run +let weakMap = new WeakMap(); + +let obj = {}; + +weakMap.set(obj, "ok"); // works fine (object key) + +*!* +// can't use a string as the key +weakMap.set("test", "Whoops"); // Error, because "test" is not an object +*/!* +``` + +Now, if we use an object as the key in it, and there are no other references to that object -- it will be removed from memory (and from the map) automatically. + +```js +let john = { name: "John" }; + +let weakMap = new WeakMap(); +weakMap.set(john, "..."); + +john = null; // overwrite the reference + +// john is removed from memory! +``` + +Compare it with the regular `Map` example above. Now if `john` only exists as the key of `WeakMap` -- it will be automatically deleted from the map (and memory). + +`WeakMap` does not support iteration and methods `keys()`, `values()`, `entries()`, so there's no way to get all keys or values from it. + +`WeakMap` has only the following methods: + +- `weakMap.get(key)` +- `weakMap.set(key, value)` +- `weakMap.delete(key)` +- `weakMap.has(key)` + +Why such a limitation? That's for technical reasons. If an object has lost all other references (like `john` in the code above), then it is to be garbage-collected automatically. But technically it's not exactly specified *when the cleanup happens*. + +The JavaScript engine decides that. It may choose to perform the memory cleanup immediately or to wait and do the cleaning later when more deletions happen. So, technically the current element count of a `WeakMap` is not known. The engine may have cleaned it up or not, or did it partially. For that reason, methods that access all keys/values are not supported. + +Now where do we need such data structure? + +## Use case: additional data + +The main area of application for `WeakMap` is an *additional data storage*. + +If we're working with an object that "belongs" to another code, maybe even a third-party library, and would like to store some data associated with it, that should only exist while the object is alive - then `WeakMap` is exactly what's needed. + +We put the data to a `WeakMap`, using the object as the key, and when the object is garbage collected, that data will automatically disappear as well. + +```js +weakMap.set(john, "secret documents"); +// if john dies, secret documents will be destroyed automatically +``` + +Let's look at an example. + +For instance, we have code that keeps a visit count for users. The information is stored in a map: a user object is the key and the visit count is the value. When a user leaves (its object gets garbage collected), we don't want to store their visit count anymore. + +Here's an example of a counting function with `Map`: + +```js +// 📁 visitsCount.js +let visitsCountMap = new Map(); // map: user => visits count + +// increase the visits count +function countUser(user) { + let count = visitsCountMap.get(user) || 0; + visitsCountMap.set(user, count + 1); +} +``` + +And here's another part of the code, maybe another file using it: + +```js +// 📁 main.js +let john = { name: "John" }; + +countUser(john); // count his visits +countUser(john); + +// later john leaves us +john = null; +``` + +Now `john` object should be garbage collected, but remains is memory, as it's a key in `visitsCountMap`. + +We need to clean `visitsCountMap` when we remove users, otherwise it will grow in memory indefinitely. Such cleaning can become a tedious task in complex architectures. + +We can avoid it by switching to `WeakMap` instead: + +```js +// 📁 visitsCount.js +let visitsCountMap = new WeakMap(); // weakmap: user => visits count + +// increase the visits count +function countUser(user) { + let count = visitsCountMap.get(user) || 0; + visitsCountMap.set(user, count + 1); +} +``` + +Now we don't have to clean `visitsCountMap`. After `john` object becomes unreachable by all means except as a key of `WeakMap`, it gets removed from memory, along with the information by that key from `WeakMap`. + +## Use case: caching + +Another common example is caching: when a function result should be remembered ("cached"), so that future calls on the same object reuse it. + +We can use `Map` to store results, like this: + +```js run +// 📁 cache.js +let cache = new Map(); + +// calculate and remember the result +function process(obj) { + if (!cache.has(obj)) { + let result = /* calculations of the result for */ obj; + + cache.set(obj, result); + } + + return cache.get(obj); +} + +*!* +// Now we use process() in another file: +*/!* + +// 📁 main.js +let obj = {/* let's say we have an object */}; + +let result1 = process(obj); // calculated + +// ...later, from another place of the code... +let result2 = process(obj); // remembered result taken from cache + +// ...later, when the object is not needed any more: +obj = null; + +alert(cache.size); // 1 (Ouch! The object is still in cache, taking memory!) +``` + +For multiple calls of `process(obj)` with the same object, it only calculates the result the first time, and then just takes it from `cache`. The downside is that we need to clean `cache` when the object is not needed any more. + +If we replace `Map` with `WeakMap`, then this problem disappears: the cached result will be removed from memory automatically after the object gets garbage collected. + +```js run +// 📁 cache.js +*!* +let cache = new WeakMap(); +*/!* + +// calculate and remember the result +function process(obj) { + if (!cache.has(obj)) { + let result = /* calculate the result for */ obj; + + cache.set(obj, result); + } + + return cache.get(obj); +} + +// 📁 main.js +let obj = {/* some object */}; + +let result1 = process(obj); +let result2 = process(obj); + +// ...later, when the object is not needed any more: +obj = null; + +// Can't get cache.size, as it's a WeakMap, +// but it's 0 or soon be 0 +// When obj gets garbage collected, cached data will be removed as well +``` + +## WeakSet + +`WeakSet` behaves similarly: + +- It is analogous to `Set`, but we may only add objects to `WeakSet` (not primitives). +- An object exists in the set while it is reachable from somewhere else. +- Like `Set`, it supports `add`, `has` and `delete`, but not `size`, `keys()` and no iterations. + +Being "weak", it also serves as an additional storage. But not for an arbitrary data, but rather for "yes/no" facts. A membership in `WeakSet` may mean something about the object. + +For instance, we can add users to `WeakSet` to keep track of those who visited our site: + +```js run +let visitedSet = new WeakSet(); + +let john = { name: "John" }; +let pete = { name: "Pete" }; +let mary = { name: "Mary" }; + +visitedSet.add(john); // John visited us +visitedSet.add(pete); // Then Pete +visitedSet.add(john); // John again + +// visitedSet has 2 users now + +// check if John visited? +alert(visitedSet.has(john)); // true + +// check if Mary visited? +alert(visitedSet.has(mary)); // false + +john = null; + +// visitedSet will be cleaned automatically +``` + +The most notable limitation of `WeakMap` and `WeakSet` is the absence of iterations, and inability to get all current content. That may appear inconvenient, but does not prevent `WeakMap/WeakSet` from doing their main job -- be an "additional" storage of data for objects which are stored/managed at another place. + +## Summary + +`WeakMap` is `Map`-like collection that allows only objects as keys and removes them together with associated value once they become inaccessible by other means. + +`WeakSet` is `Set`-like collection that stores only objects and removes them once they become inaccessible by other means. + +Both of them do not support methods and properties that refer to all keys or their count. Only individual operations are allowed. + +`WeakMap` and `WeakSet` are used as "secondary" data structures in addition to the "main" object storage. Once the object is removed from the main storage, if it is only found as the key of `WeakMap` or in a `WeakSet`, it will be cleaned up automatically. diff --git a/1-js/05-data-types/09-destructuring-assignment/destructuring-complex.png b/1-js/05-data-types/09-destructuring-assignment/destructuring-complex.png deleted file mode 100644 index c46bf6e45..000000000 Binary files a/1-js/05-data-types/09-destructuring-assignment/destructuring-complex.png and /dev/null differ diff --git a/1-js/05-data-types/09-destructuring-assignment/destructuring-complex@2x.png b/1-js/05-data-types/09-destructuring-assignment/destructuring-complex@2x.png deleted file mode 100644 index 26032a3d6..000000000 Binary files a/1-js/05-data-types/09-destructuring-assignment/destructuring-complex@2x.png and /dev/null differ diff --git a/1-js/05-data-types/08-keys-values-entries/01-sum-salaries/_js.view/solution.js b/1-js/05-data-types/09-keys-values-entries/01-sum-salaries/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/01-sum-salaries/_js.view/solution.js rename to 1-js/05-data-types/09-keys-values-entries/01-sum-salaries/_js.view/solution.js diff --git a/1-js/05-data-types/08-keys-values-entries/01-sum-salaries/_js.view/test.js b/1-js/05-data-types/09-keys-values-entries/01-sum-salaries/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/01-sum-salaries/_js.view/test.js rename to 1-js/05-data-types/09-keys-values-entries/01-sum-salaries/_js.view/test.js diff --git a/1-js/05-data-types/08-keys-values-entries/01-sum-salaries/solution.md b/1-js/05-data-types/09-keys-values-entries/01-sum-salaries/solution.md similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/01-sum-salaries/solution.md rename to 1-js/05-data-types/09-keys-values-entries/01-sum-salaries/solution.md diff --git a/1-js/05-data-types/08-keys-values-entries/01-sum-salaries/task.md b/1-js/05-data-types/09-keys-values-entries/01-sum-salaries/task.md similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/01-sum-salaries/task.md rename to 1-js/05-data-types/09-keys-values-entries/01-sum-salaries/task.md diff --git a/1-js/05-data-types/08-keys-values-entries/02-count-properties/_js.view/solution.js b/1-js/05-data-types/09-keys-values-entries/02-count-properties/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/02-count-properties/_js.view/solution.js rename to 1-js/05-data-types/09-keys-values-entries/02-count-properties/_js.view/solution.js diff --git a/1-js/05-data-types/08-keys-values-entries/02-count-properties/_js.view/test.js b/1-js/05-data-types/09-keys-values-entries/02-count-properties/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/02-count-properties/_js.view/test.js rename to 1-js/05-data-types/09-keys-values-entries/02-count-properties/_js.view/test.js diff --git a/1-js/05-data-types/08-keys-values-entries/02-count-properties/solution.md b/1-js/05-data-types/09-keys-values-entries/02-count-properties/solution.md similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/02-count-properties/solution.md rename to 1-js/05-data-types/09-keys-values-entries/02-count-properties/solution.md diff --git a/1-js/05-data-types/08-keys-values-entries/02-count-properties/task.md b/1-js/05-data-types/09-keys-values-entries/02-count-properties/task.md similarity index 100% rename from 1-js/05-data-types/08-keys-values-entries/02-count-properties/task.md rename to 1-js/05-data-types/09-keys-values-entries/02-count-properties/task.md diff --git a/1-js/05-data-types/08-keys-values-entries/article.md b/1-js/05-data-types/09-keys-values-entries/article.md similarity index 61% rename from 1-js/05-data-types/08-keys-values-entries/article.md rename to 1-js/05-data-types/09-keys-values-entries/article.md index 3780b33e5..ca0be768a 100644 --- a/1-js/05-data-types/08-keys-values-entries/article.md +++ b/1-js/05-data-types/09-keys-values-entries/article.md @@ -23,7 +23,7 @@ For plain objects, the following methods are available: - [Object.values(obj)](mdn:js/Object/values) -- returns an array of values. - [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of `[key, value]` pairs. -...But please note the distinctions (compared to map for example): +Please note the distinctions (compared to map for example): | | Map | Object | |-------------|------------------|--------------| @@ -32,7 +32,7 @@ For plain objects, the following methods are available: The first difference is that we have to call `Object.keys(obj)`, and not `obj.keys()`. -Why so? The main reason is flexibility. Remember, objects are a base of all complex structures in JavaScript. So we may have an object of our own like `order` that implements its own `order.values()` method. And we still can call `Object.values(order)` on it. +Why so? The main reason is flexibility. Remember, objects are a base of all complex structures in JavaScript. So we may have an object of our own like `data` that implements its own `data.values()` method. And we still can call `Object.values(data)` on it. The second difference is that `Object.*` methods return "real" array objects, not just an iterable. That's mainly for historical reasons. @@ -69,52 +69,18 @@ Just like a `for..in` loop, these methods ignore properties that use `Symbol(... Usually that's convenient. But if we want symbolic keys too, then there's a separate method [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols) that returns an array of only symbolic keys. Also, there exist a method [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) that returns *all* keys. ``` -## Object.fromEntries to transform objects -Sometimes we need to perform a transformation of an object to `Map` and back. +## Transforming objects -We already have `new Map(Object.entries(obj))` to make a `Map` from `obj`. +Objects lack many methods that exist for arrays, e.g. `map`, `filter` and others. -The syntax of `Object.fromEntries` does the reverse. Given an array of `[key, value]` pairs, it creates an object: +If we'd like to apply them, then we can use `Object.entries` followed `Object.fromEntries`: -```js run -let prices = Object.fromEntries([ - ['banana', 1], - ['orange', 2], - ['meat', 4] -]); - -// now prices = { banana: 1, orange: 2, meat: 4 } - -alert(prices.orange); // 2 -``` +1. Use `Object.entries(obj)` to get an array of key/value pairs from `obj`. +2. Use array methods on that array, e.g. `map`. +3. Use `Object.fromEntries(array)` on the resulting array to turn it back into an object. -Let's see practical applications. - -For example, we'd like to create a new object with double prices from the existing one. - -For arrays, we have `.map` method that allows to transform an array, but nothing like that for objects. - -So we can use a loop: - -```js run -let prices = { - banana: 1, - orange: 2, - meat: 4, -}; - -let doublePrices = {}; -for(let [product, price] of Object.entries(prices)) { - doublePrices[product] = price * 2; -} - -alert(doublePrices.meat); // 8 -``` - -...Or we can represent the object as an `Array` using `Object.entries`, then perform the operations with `map` (and potentially other array methods), and then go back using `Object.fromEntries`. - -Let's do it for our object: +For example, we have an object with prices, and would like to double them: ```js run let prices = { @@ -135,21 +101,4 @@ alert(doublePrices.meat); // 8 It may look difficult from the first sight, but becomes easy to understand after you use it once or twice. -We also can use `fromEntries` to get an object from `Map`. - -E.g. we have a `Map` of prices, but we need to pass it to a 3rd-party code that expects an object. - -Here we go: - -```js run -let map = new Map(); -map.set('banana', 1); -map.set('orange', 2); -map.set('meat', 4); - -let obj = Object.fromEntries(map); - -// now obj = { banana: 1, orange: 2, meat: 4 } - -alert(obj.orange); // 2 -``` +We can make powerful one-liners for more complex transforms this way. It's only important to keep balance, so that the code is still simple enough to understand it. diff --git a/1-js/05-data-types/10-date/1-new-date/solution.md b/1-js/05-data-types/10-date/1-new-date/solution.md deleted file mode 100644 index eb271a91a..000000000 --- a/1-js/05-data-types/10-date/1-new-date/solution.md +++ /dev/null @@ -1,8 +0,0 @@ -The `new Date` constructor uses the local time zone by default. So the only important thing to remember is that months start from zero. - -So February has number 1. - -```js run -let d = new Date(2012, 1, 20, 3, 12); -alert( d ); -``` diff --git a/1-js/05-data-types/09-destructuring-assignment/1-destruct-user/solution.md b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/1-destruct-user/solution.md rename to 1-js/05-data-types/10-destructuring-assignment/1-destruct-user/solution.md diff --git a/1-js/05-data-types/09-destructuring-assignment/1-destruct-user/task.md b/1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/1-destruct-user/task.md rename to 1-js/05-data-types/10-destructuring-assignment/1-destruct-user/task.md diff --git a/1-js/05-data-types/09-destructuring-assignment/6-max-salary/_js.view/solution.js b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/6-max-salary/_js.view/solution.js rename to 1-js/05-data-types/10-destructuring-assignment/6-max-salary/_js.view/solution.js diff --git a/1-js/05-data-types/09-destructuring-assignment/6-max-salary/_js.view/test.js b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/6-max-salary/_js.view/test.js rename to 1-js/05-data-types/10-destructuring-assignment/6-max-salary/_js.view/test.js diff --git a/1-js/05-data-types/09-destructuring-assignment/6-max-salary/solution.md b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/solution.md similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/6-max-salary/solution.md rename to 1-js/05-data-types/10-destructuring-assignment/6-max-salary/solution.md diff --git a/1-js/05-data-types/09-destructuring-assignment/6-max-salary/task.md b/1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md similarity index 100% rename from 1-js/05-data-types/09-destructuring-assignment/6-max-salary/task.md rename to 1-js/05-data-types/10-destructuring-assignment/6-max-salary/task.md diff --git a/1-js/05-data-types/09-destructuring-assignment/article.md b/1-js/05-data-types/10-destructuring-assignment/article.md similarity index 88% rename from 1-js/05-data-types/09-destructuring-assignment/article.md rename to 1-js/05-data-types/10-destructuring-assignment/article.md index a87fd5b5a..dec2535a3 100644 --- a/1-js/05-data-types/09-destructuring-assignment/article.md +++ b/1-js/05-data-types/10-destructuring-assignment/article.md @@ -262,7 +262,7 @@ alert(height); // 200 Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided. -The code below asks for width, but not the title. +In the code below `prompt` asks for `width`, but not for `title`: ```js run let options = { @@ -274,7 +274,7 @@ let {width = prompt("width?"), title = prompt("title?")} = options; */!* alert(title); // Menu -alert(width); // (whatever you the result of prompt is) +alert(width); // (whatever the result of prompt is) ``` We also can combine both the colon and equality: @@ -293,6 +293,21 @@ alert(w); // 100 alert(h); // 200 ``` +If we have a complex object with many properties, we can extract only what we need: + +```js run +let options = { + title: "Menu", + width: 100, + height: 200 +}; + +// only extract title as a variable +let { title } = options; + +alert(title); // Menu +``` + ### The rest pattern "..." What if the object has more properties than we have variables? Can we take some and then assign the "rest" somewhere? @@ -319,8 +334,6 @@ alert(rest.height); // 200 alert(rest.width); // 100 ``` - - ````smart header="Gotcha if there's no `let`" In the examples above variables were declared right in the assignment: `let {…} = {…}`. Of course, we could use existing variables too, without `let`. But there's a catch. @@ -343,24 +356,25 @@ The problem is that JavaScript treats `{...}` in the main code flow (not inside } ``` -To show JavaScript that it's not a code block, we can make it a part of an expression by wrapping in parentheses `(...)`: +So here JavaScript assumes that we have a code block, that's why there's an error. We have destructuring instead. + +To show JavaScript that it's not a code block, we can wrap the expression in parentheses `(...)`: ```js run let title, width, height; // okay now -*!*(*/!*{title, width, height}*!*)*/!* = {title: "Menu", width: 200, height: 100}; +*!*(*/!*{title, width, height} = {title: "Menu", width: 200, height: 100}*!*)*/!*; alert( title ); // Menu ``` - ```` ## Nested destructuring -If an object or an array contain other objects and arrays, we can use more complex left-side patterns to extract deeper portions. +If an object or an array contain other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions. -In the code below `options` has another object in the property `size` and an array in the property `items`. The pattern at the left side of the assignment has the same structure: +In the code below `options` has another object in the property `size` and an array in the property `items`. The pattern at the left side of the assignment has the same structure to extract values from them: ```js run let options = { @@ -369,7 +383,7 @@ let options = { height: 200 }, items: ["Cake", "Donut"], - extra: true // something extra that we will not destruct + extra: true }; // destructuring assignment split in multiple lines for clarity @@ -389,20 +403,13 @@ alert(item1); // Cake alert(item2); // Donut ``` -The whole `options` object except `extra` that was not mentioned, is assigned to corresponding variables. - -Note that `size` and `items` itself is not destructured. +The whole `options` object except `extra` that was not mentioned, is assigned to corresponding variables: -![](destructuring-complex.png) +![](destructuring-complex.svg) Finally, we have `width`, `height`, `item1`, `item2` and `title` from the default value. -If we have a complex object with many properties, we can extract only what we need: - -```js -// take size as a whole into a variable, ignore the rest -let { size } = options; -``` +Note that there are no variables for `size` and `items`, as we take their content instead. ## Smart function parameters @@ -421,6 +428,7 @@ In real-life, the problem is how to remember the order of arguments. Usually IDE Like this? ```js +// undefined where default values are fine showMenu("My Menu", undefined, undefined, ["Item1", "Item2"]) ``` @@ -472,29 +480,28 @@ function showMenu({ showMenu(options); ``` -The syntax is the same as for a destructuring assignment: +The full syntax is the same as for a destructuring assignment: ```js function({ - incomingProperty: parameterName = defaultValue + incomingProperty: varName = defaultValue ... }) ``` +Then, for an object of parameters, there will be a variable `varName` for property `incomingProperty`, with `defaultValue` by default. + Please note that such destructuring assumes that `showMenu()` does have an argument. If we want all values by default, then we should specify an empty object: ```js -showMenu({}); - +showMenu({}); // ok, all values are default showMenu(); // this would give an error ``` -We can fix this by making `{}` the default value for the whole destructuring thing: - +We can fix this by making `{}` the default value for the whole object of parameters: ```js run -// simplified parameters a bit for clarity -function showMenu(*!*{ title = "Menu", width = 100, height = 200 } = {}*/!*) { +function showMenu({ title = "Menu", width = 100, height = 200 }*!* = {}*/!*) { alert( `${title} ${width} ${height}` ); } @@ -506,7 +513,7 @@ In the code above, the whole arguments object is `{}` by default, so there's alw ## Summary - Destructuring assignment allows for instantly mapping an object or array onto many variables. -- The object syntax: +- The full object syntax: ```js let {prop : varName = default, ...rest} = object ``` @@ -515,7 +522,7 @@ In the code above, the whole arguments object is `{}` by default, so there's alw Object properties that have no mapping are copied to the `rest` object. -- The array syntax: +- The full array syntax: ```js let [item1 = default, item2, ...rest] = array @@ -523,4 +530,4 @@ In the code above, the whole arguments object is `{}` by default, so there's alw The first item goes to `item1`; the second goes into `item2`, all the rest makes the array `rest`. -- For more complex cases, the left side must have the same structure as the right one. +- It's possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one. diff --git a/1-js/05-data-types/10-destructuring-assignment/destructuring-complex.svg b/1-js/05-data-types/10-destructuring-assignment/destructuring-complex.svg new file mode 100644 index 000000000..0b650020b --- /dev/null +++ b/1-js/05-data-types/10-destructuring-assignment/destructuring-complex.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/1-js/05-data-types/11-date/1-new-date/solution.md b/1-js/05-data-types/11-date/1-new-date/solution.md new file mode 100644 index 000000000..9bb1d749c --- /dev/null +++ b/1-js/05-data-types/11-date/1-new-date/solution.md @@ -0,0 +1,8 @@ +The `new Date` constructor uses the local time zone. So the only important thing to remember is that months start from zero. + +So February has number 1. + +```js run +let d = new Date(2012, 1, 20, 3, 12); +alert( d ); +``` diff --git a/1-js/05-data-types/10-date/1-new-date/task.md b/1-js/05-data-types/11-date/1-new-date/task.md similarity index 100% rename from 1-js/05-data-types/10-date/1-new-date/task.md rename to 1-js/05-data-types/11-date/1-new-date/task.md diff --git a/1-js/05-data-types/10-date/2-get-week-day/_js.view/solution.js b/1-js/05-data-types/11-date/2-get-week-day/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/10-date/2-get-week-day/_js.view/solution.js rename to 1-js/05-data-types/11-date/2-get-week-day/_js.view/solution.js diff --git a/1-js/05-data-types/10-date/2-get-week-day/_js.view/test.js b/1-js/05-data-types/11-date/2-get-week-day/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/10-date/2-get-week-day/_js.view/test.js rename to 1-js/05-data-types/11-date/2-get-week-day/_js.view/test.js diff --git a/1-js/05-data-types/10-date/2-get-week-day/solution.md b/1-js/05-data-types/11-date/2-get-week-day/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/2-get-week-day/solution.md rename to 1-js/05-data-types/11-date/2-get-week-day/solution.md diff --git a/1-js/05-data-types/10-date/2-get-week-day/task.md b/1-js/05-data-types/11-date/2-get-week-day/task.md similarity index 100% rename from 1-js/05-data-types/10-date/2-get-week-day/task.md rename to 1-js/05-data-types/11-date/2-get-week-day/task.md diff --git a/1-js/05-data-types/10-date/3-weekday/_js.view/solution.js b/1-js/05-data-types/11-date/3-weekday/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/10-date/3-weekday/_js.view/solution.js rename to 1-js/05-data-types/11-date/3-weekday/_js.view/solution.js diff --git a/1-js/05-data-types/10-date/3-weekday/_js.view/test.js b/1-js/05-data-types/11-date/3-weekday/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/10-date/3-weekday/_js.view/test.js rename to 1-js/05-data-types/11-date/3-weekday/_js.view/test.js diff --git a/1-js/05-data-types/10-date/3-weekday/solution.md b/1-js/05-data-types/11-date/3-weekday/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/3-weekday/solution.md rename to 1-js/05-data-types/11-date/3-weekday/solution.md diff --git a/1-js/05-data-types/10-date/3-weekday/task.md b/1-js/05-data-types/11-date/3-weekday/task.md similarity index 100% rename from 1-js/05-data-types/10-date/3-weekday/task.md rename to 1-js/05-data-types/11-date/3-weekday/task.md diff --git a/1-js/05-data-types/10-date/4-get-date-ago/_js.view/solution.js b/1-js/05-data-types/11-date/4-get-date-ago/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/10-date/4-get-date-ago/_js.view/solution.js rename to 1-js/05-data-types/11-date/4-get-date-ago/_js.view/solution.js diff --git a/1-js/05-data-types/10-date/4-get-date-ago/_js.view/test.js b/1-js/05-data-types/11-date/4-get-date-ago/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/10-date/4-get-date-ago/_js.view/test.js rename to 1-js/05-data-types/11-date/4-get-date-ago/_js.view/test.js diff --git a/1-js/05-data-types/10-date/4-get-date-ago/solution.md b/1-js/05-data-types/11-date/4-get-date-ago/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/4-get-date-ago/solution.md rename to 1-js/05-data-types/11-date/4-get-date-ago/solution.md diff --git a/1-js/05-data-types/10-date/4-get-date-ago/task.md b/1-js/05-data-types/11-date/4-get-date-ago/task.md similarity index 92% rename from 1-js/05-data-types/10-date/4-get-date-ago/task.md rename to 1-js/05-data-types/11-date/4-get-date-ago/task.md index 40dcd926d..058d39c7e 100644 --- a/1-js/05-data-types/10-date/4-get-date-ago/task.md +++ b/1-js/05-data-types/11-date/4-get-date-ago/task.md @@ -8,7 +8,7 @@ Create a function `getDateAgo(date, days)` to return the day of month `days` ago For instance, if today is 20th, then `getDateAgo(new Date(), 1)` should be 19th and `getDateAgo(new Date(), 2)` should be 18th. -Should also work over months/years reliably: +Should work reliably for `days=365` or more: ```js let date = new Date(2015, 0, 2); diff --git a/1-js/05-data-types/10-date/5-last-day-of-month/_js.view/solution.js b/1-js/05-data-types/11-date/5-last-day-of-month/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/10-date/5-last-day-of-month/_js.view/solution.js rename to 1-js/05-data-types/11-date/5-last-day-of-month/_js.view/solution.js diff --git a/1-js/05-data-types/10-date/5-last-day-of-month/_js.view/test.js b/1-js/05-data-types/11-date/5-last-day-of-month/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/10-date/5-last-day-of-month/_js.view/test.js rename to 1-js/05-data-types/11-date/5-last-day-of-month/_js.view/test.js diff --git a/1-js/05-data-types/10-date/5-last-day-of-month/solution.md b/1-js/05-data-types/11-date/5-last-day-of-month/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/5-last-day-of-month/solution.md rename to 1-js/05-data-types/11-date/5-last-day-of-month/solution.md diff --git a/1-js/05-data-types/10-date/5-last-day-of-month/task.md b/1-js/05-data-types/11-date/5-last-day-of-month/task.md similarity index 100% rename from 1-js/05-data-types/10-date/5-last-day-of-month/task.md rename to 1-js/05-data-types/11-date/5-last-day-of-month/task.md diff --git a/1-js/05-data-types/10-date/6-get-seconds-today/solution.md b/1-js/05-data-types/11-date/6-get-seconds-today/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/6-get-seconds-today/solution.md rename to 1-js/05-data-types/11-date/6-get-seconds-today/solution.md diff --git a/1-js/05-data-types/10-date/6-get-seconds-today/task.md b/1-js/05-data-types/11-date/6-get-seconds-today/task.md similarity index 100% rename from 1-js/05-data-types/10-date/6-get-seconds-today/task.md rename to 1-js/05-data-types/11-date/6-get-seconds-today/task.md diff --git a/1-js/05-data-types/10-date/7-get-seconds-to-tomorrow/solution.md b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/7-get-seconds-to-tomorrow/solution.md rename to 1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/solution.md diff --git a/1-js/05-data-types/10-date/7-get-seconds-to-tomorrow/task.md b/1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md similarity index 100% rename from 1-js/05-data-types/10-date/7-get-seconds-to-tomorrow/task.md rename to 1-js/05-data-types/11-date/7-get-seconds-to-tomorrow/task.md diff --git a/1-js/05-data-types/10-date/8-format-date-relative/_js.view/solution.js b/1-js/05-data-types/11-date/8-format-date-relative/_js.view/solution.js similarity index 100% rename from 1-js/05-data-types/10-date/8-format-date-relative/_js.view/solution.js rename to 1-js/05-data-types/11-date/8-format-date-relative/_js.view/solution.js diff --git a/1-js/05-data-types/10-date/8-format-date-relative/_js.view/test.js b/1-js/05-data-types/11-date/8-format-date-relative/_js.view/test.js similarity index 100% rename from 1-js/05-data-types/10-date/8-format-date-relative/_js.view/test.js rename to 1-js/05-data-types/11-date/8-format-date-relative/_js.view/test.js diff --git a/1-js/05-data-types/10-date/8-format-date-relative/solution.md b/1-js/05-data-types/11-date/8-format-date-relative/solution.md similarity index 100% rename from 1-js/05-data-types/10-date/8-format-date-relative/solution.md rename to 1-js/05-data-types/11-date/8-format-date-relative/solution.md diff --git a/1-js/05-data-types/10-date/8-format-date-relative/task.md b/1-js/05-data-types/11-date/8-format-date-relative/task.md similarity index 94% rename from 1-js/05-data-types/10-date/8-format-date-relative/task.md rename to 1-js/05-data-types/11-date/8-format-date-relative/task.md index 7b341ca2e..4dc067375 100644 --- a/1-js/05-data-types/10-date/8-format-date-relative/task.md +++ b/1-js/05-data-types/11-date/8-format-date-relative/task.md @@ -20,6 +20,6 @@ alert( formatDate(new Date(new Date - 30 * 1000)) ); // "30 sec. ago" alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "5 min. ago" -// yesterday's date like 31.12.2016, 20:00 +// yesterday's date like 31.12.16, 20:00 alert( formatDate(new Date(new Date - 86400 * 1000)) ); ``` diff --git a/1-js/05-data-types/10-date/article.md b/1-js/05-data-types/11-date/article.md similarity index 87% rename from 1-js/05-data-types/10-date/article.md rename to 1-js/05-data-types/11-date/article.md index 8a75f1cbd..4f80f752b 100644 --- a/1-js/05-data-types/10-date/article.md +++ b/1-js/05-data-types/11-date/article.md @@ -29,18 +29,17 @@ To create a new `Date` object call `new Date()` with one of the following argume alert( Jan02_1970 ); ``` - The number of milliseconds that has passed since the beginning of 1970 is called a *timestamp*. + An integer number representing the number of milliseconds that has passed since the beginning of 1970 is called a *timestamp*. It's a lightweight numeric representation of a date. We can always create a date from a timestamp using `new Date(timestamp)` and convert the existing `Date` object to a timestamp using the `date.getTime()` method (see below). `new Date(datestring)` -: If there is a single argument, and it's a string, then it is parsed with the `Date.parse` algorithm (see below). - +: If there is a single argument, and it's a string, then it is parsed automatically. The algorithm is the same as `Date.parse` uses, we'll cover it later. ```js run let date = new Date("2017-01-26"); alert(date); - // The time portion of the date is assumed to be midnight GMT and + // The time is not set, so it's assumed to be midnight GMT and // is adjusted according to the timezone the code is run in // So the result could be // Thu Jan 26 2017 11:00:00 GMT+1100 (Australian Eastern Daylight Time) @@ -49,9 +48,7 @@ To create a new `Date` object call `new Date()` with one of the following argume ``` `new Date(year, month, date, hours, minutes, seconds, ms)` -: Create the date with the given components in the local time zone. Only two first arguments are obligatory. - - Note: +: Create the date with the given components in the local time zone. Only the first two arguments are obligatory. - The `year` must have 4 digits: `2013` is okay, `98` is not. - The `month` count starts with `0` (Jan), up to `11` (Dec). @@ -74,7 +71,7 @@ To create a new `Date` object call `new Date()` with one of the following argume ## Access date components -There are many methods to access the year, month and so on from the `Date` object. But they can be easily remembered when categorized. +There are methods to access the year, month and so on from the `Date` object: [getFullYear()](mdn:js/Date/getFullYear) : Get the year (4 digits) @@ -133,12 +130,12 @@ Besides the given methods, there are two special ones that do not have a UTC-var The following methods allow to set date/time components: -- [`setFullYear(year [, month, date])`](mdn:js/Date/setFullYear) -- [`setMonth(month [, date])`](mdn:js/Date/setMonth) +- [`setFullYear(year, [month], [date])`](mdn:js/Date/setFullYear) +- [`setMonth(month, [date])`](mdn:js/Date/setMonth) - [`setDate(date)`](mdn:js/Date/setDate) -- [`setHours(hour [, min, sec, ms])`](mdn:js/Date/setHours) -- [`setMinutes(min [, sec, ms])`](mdn:js/Date/setMinutes) -- [`setSeconds(sec [, ms])`](mdn:js/Date/setSeconds) +- [`setHours(hour, [min], [sec], [ms])`](mdn:js/Date/setHours) +- [`setMinutes(min, [sec], [ms])`](mdn:js/Date/setMinutes) +- [`setSeconds(sec, [ms])`](mdn:js/Date/setSeconds) - [`setMilliseconds(ms)`](mdn:js/Date/setMilliseconds) - [`setTime(milliseconds)`](mdn:js/Date/setTime) (sets the whole date by milliseconds since 01.01.1970 UTC) @@ -217,21 +214,21 @@ The important side effect: dates can be subtracted, the result is their differen That can be used for time measurements: ```js run -let start = new Date(); // start counting +let start = new Date(); // start measuring time // do the job for (let i = 0; i < 100000; i++) { let doSomething = i * i * i; } -let end = new Date(); // done +let end = new Date(); // end measuring time alert( `The loop took ${end - start} ms` ); ``` ## Date.now() -If we only want to measure the difference, we don't need the `Date` object. +If we only want to measure time, we don't need the `Date` object. There's a special method `Date.now()` that returns the current timestamp. @@ -264,6 +261,8 @@ If we want a reliable benchmark of CPU-hungry function, we should be careful. For instance, let's measure two functions that calculate the difference between two dates: which one is faster? +Such performance measurements are often called "benchmarks". + ```js // we have date1 and date2, which function faster returns their difference in ms? function diffSubtract(date1, date2) { @@ -280,7 +279,7 @@ These two do exactly the same thing, but one of them uses an explicit `date.getT So, which one is faster? -The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it around 100000 times. +The first idea may be to run them many times in a row and measure the time difference. For our case, functions are very simple, so we have to do it at least 100000 times. Let's measure: @@ -310,7 +309,7 @@ Wow! Using `getTime()` is so much faster! That's because there's no type convers Okay, we have something. But that's not a good benchmark yet. -Imagine that at the time of running `bench(diffSubtract)` CPU was doing something in parallel, and it was taking resources. And by the time of running `bench(diffGetTime)` the work has finished. +Imagine that at the time of running `bench(diffSubtract)` CPU was doing something in parallel, and it was taking resources. And by the time of running `bench(diffGetTime)` that work has finished. A pretty real scenario for a modern multi-process OS. @@ -318,7 +317,7 @@ As a result, the first benchmark will have less CPU resources than the second. T **For more reliable benchmarking, the whole pack of benchmarks should be rerun multiple times.** -Here's the code example: +For example, like this: ```js run function diffSubtract(date1, date2) { @@ -368,7 +367,7 @@ for (let i = 0; i < 10; i++) { ``` ```warn header="Be careful doing microbenchmarking" -Modern JavaScript engines perform many optimizations. They may tweak results of "artificial tests" compared to "normal usage", especially when we benchmark something very small. So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won't need microbenchmarks at all. +Modern JavaScript engines perform many optimizations. They may tweak results of "artificial tests" compared to "normal usage", especially when we benchmark something very small, such as how an operator works, or a built-in function. So if you seriously want to understand performance, then please study how the JavaScript engine works. And then you probably won't need microbenchmarks at all. The great pack of articles about V8 can be found at . ``` @@ -415,7 +414,7 @@ alert(date); Note that unlike many other systems, timestamps in JavaScript are in milliseconds, not in seconds. -Also, sometimes we need more precise time measurements. JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but most environments provide it. For instance, browser has [performance.now()](mdn:api/Performance/now) that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point): +Sometimes we need more precise time measurements. JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but most environments provide it. For instance, browser has [performance.now()](mdn:api/Performance/now) that gives the number of milliseconds from the start of page loading with microsecond precision (3 digits after the point): ```js run alert(`Loading started ${performance.now()}ms ago`); @@ -424,4 +423,4 @@ alert(`Loading started ${performance.now()}ms ago`); // more than 3 digits after the decimal point are precision errors, but only the first 3 are correct ``` -Node.js has `microtime` module and other ways. Technically, any device and environment allows to get more precision, it's just not in `Date`. +Node.js has `microtime` module and other ways. Technically, almost any device and environment allows to get more precision, it's just not in `Date`. diff --git a/1-js/05-data-types/11-json/json-meetup.png b/1-js/05-data-types/11-json/json-meetup.png deleted file mode 100644 index 268666424..000000000 Binary files a/1-js/05-data-types/11-json/json-meetup.png and /dev/null differ diff --git a/1-js/05-data-types/11-json/json-meetup@2x.png b/1-js/05-data-types/11-json/json-meetup@2x.png deleted file mode 100644 index a8f2cd609..000000000 Binary files a/1-js/05-data-types/11-json/json-meetup@2x.png and /dev/null differ diff --git a/1-js/05-data-types/11-json/1-serialize-object/solution.md b/1-js/05-data-types/12-json/1-serialize-object/solution.md similarity index 100% rename from 1-js/05-data-types/11-json/1-serialize-object/solution.md rename to 1-js/05-data-types/12-json/1-serialize-object/solution.md diff --git a/1-js/05-data-types/11-json/1-serialize-object/task.md b/1-js/05-data-types/12-json/1-serialize-object/task.md similarity index 100% rename from 1-js/05-data-types/11-json/1-serialize-object/task.md rename to 1-js/05-data-types/12-json/1-serialize-object/task.md diff --git a/1-js/05-data-types/11-json/2-serialize-event-circular/solution.md b/1-js/05-data-types/12-json/2-serialize-event-circular/solution.md similarity index 100% rename from 1-js/05-data-types/11-json/2-serialize-event-circular/solution.md rename to 1-js/05-data-types/12-json/2-serialize-event-circular/solution.md diff --git a/1-js/05-data-types/11-json/2-serialize-event-circular/task.md b/1-js/05-data-types/12-json/2-serialize-event-circular/task.md similarity index 79% rename from 1-js/05-data-types/11-json/2-serialize-event-circular/task.md rename to 1-js/05-data-types/12-json/2-serialize-event-circular/task.md index 8b3963ddf..3755a24aa 100644 --- a/1-js/05-data-types/11-json/2-serialize-event-circular/task.md +++ b/1-js/05-data-types/12-json/2-serialize-event-circular/task.md @@ -6,7 +6,7 @@ importance: 5 In simple cases of circular references, we can exclude an offending property from serialization by its name. -But sometimes there are many backreferences. And names may be used both in circular references and normal properties. +But sometimes we can't just use the name, as it may be used both in circular references and normal properties. So we can check the property by its value. Write `replacer` function to stringify everything, but remove properties that reference `meetup`: @@ -22,7 +22,7 @@ let meetup = { }; *!* -// circular references +// circular references room.occupiedBy = meetup; meetup.self = meetup; */!* @@ -39,4 +39,3 @@ alert( JSON.stringify(meetup, function replacer(key, value) { } */ ``` - diff --git a/1-js/05-data-types/11-json/article.md b/1-js/05-data-types/12-json/article.md similarity index 90% rename from 1-js/05-data-types/11-json/article.md rename to 1-js/05-data-types/12-json/article.md index cce3d1df9..a701c76bb 100644 --- a/1-js/05-data-types/11-json/article.md +++ b/1-js/05-data-types/12-json/article.md @@ -21,7 +21,7 @@ let user = { alert(user); // {name: "John", age: 30} ``` -...But in the process of development, new properties are added, old properties are renamed and removed. Updating such `toString` every time can become a pain. We could try to loop over properties in it, but what if the object is complex and has nested objects in properties? We'd need to implement their conversion as well. And, if we're sending the object over a network, then we also need to supply the code to "read" our object on the receiving side. +...But in the process of development, new properties are added, old properties are renamed and removed. Updating such `toString` every time can become a pain. We could try to loop over properties in it, but what if the object is complex and has nested objects in properties? We'd need to implement their conversion as well. Luckily, there's no need to write the code to handle all this. The task has been solved already. @@ -76,7 +76,7 @@ Please note that a JSON-encoded object has several important differences from th `JSON.stringify` can be applied to primitives as well. -Natively supported JSON types are: +JSON supports following data types: - Objects `{ ... }` - Arrays `[ ... ]` @@ -100,7 +100,7 @@ alert( JSON.stringify(true) ); // true alert( JSON.stringify([1, 2, 3]) ); // [1,2,3] ``` -JSON is data-only cross-language specification, so some JavaScript-specific object properties are skipped by `JSON.stringify`. +JSON is data-only language-independent specification, so some JavaScript-specific object properties are skipped by `JSON.stringify`. Namely: @@ -170,7 +170,7 @@ JSON.stringify(meetup); // Error: Converting circular structure to JSON Here, the conversion fails, because of circular reference: `room.occupiedBy` references `meetup`, and `meetup.place` references `room`: -![](json-meetup.png) +![](json-meetup.svg) ## Excluding and transforming: replacer @@ -213,9 +213,9 @@ alert( JSON.stringify(meetup, *!*['title', 'participants']*/!*) ); // {"title":"Conference","participants":[{},{}]} ``` -Here we are probably too strict. The property list is applied to the whole object structure. So participants are empty, because `name` is not in the list. +Here we are probably too strict. The property list is applied to the whole object structure. So the objects in `participants` are empty, because `name` is not in the list. -Let's include every property except `room.occupiedBy` that would cause the circular reference: +Let's include in the list every property except `room.occupiedBy` that would cause the circular reference: ```js run let room = { @@ -244,7 +244,7 @@ Now everything except `occupiedBy` is serialized. But the list of properties is Fortunately, we can use a function instead of an array as the `replacer`. -The function will be called for every `(key, value)` pair and should return the "replaced" value, which will be used instead of the original one. +The function will be called for every `(key, value)` pair and should return the "replaced" value, which will be used instead of the original one. Or `undefined` if the value is to be skipped. In our case, we can return `value` "as is" for everything except `occupiedBy`. To ignore `occupiedBy`, the code below returns `undefined`: @@ -262,7 +262,7 @@ let meetup = { room.occupiedBy = meetup; // room references meetup alert( JSON.stringify(meetup, function replacer(key, value) { - alert(`${key}: ${value}`); // to see what replacer gets + alert(`${key}: ${value}`); return (key == 'occupiedBy') ? undefined : value; })); @@ -283,16 +283,16 @@ Please note that `replacer` function gets every key/value pair including nested The first call is special. It is made using a special "wrapper object": `{"": meetup}`. In other words, the first `(key, value)` pair has an empty key, and the value is the target object as a whole. That's why the first line is `":[object Object]"` in the example above. -The idea is to provide as much power for `replacer` as possible: it has a chance to analyze and replace/skip the whole object if necessary. +The idea is to provide as much power for `replacer` as possible: it has a chance to analyze and replace/skip even the whole object if necessary. -## Formatting: spacer +## Formatting: space -The third argument of `JSON.stringify(value, replacer, spaces)` is the number of spaces to use for pretty formatting. +The third argument of `JSON.stringify(value, replacer, space)` is the number of spaces to use for pretty formatting. -Previously, all stringified objects had no indents and extra spaces. That's fine if we want to send an object over a network. The `spacer` argument is used exclusively for a nice output. +Previously, all stringified objects had no indents and extra spaces. That's fine if we want to send an object over a network. The `space` argument is used exclusively for a nice output. -Here `spacer = 2` tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside an object: +Here `space = 2` tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside an object: ```js run let user = { @@ -328,7 +328,7 @@ alert(JSON.stringify(user, null, 2)); */ ``` -The `spaces` parameter is used solely for logging and nice-output purposes. +The `space` parameter is used solely for logging and nice-output purposes. ## Custom "toJSON" @@ -393,7 +393,7 @@ alert( JSON.stringify(meetup) ); */ ``` -As we can see, `toJSON` is used both for the direct call `JSON.stringify(room)` and for the nested object. +As we can see, `toJSON` is used both for the direct call `JSON.stringify(room)` and when `room` is nested is another encoded object. ## JSON.parse @@ -402,7 +402,7 @@ To decode a JSON-string, we need another method named [JSON.parse](mdn:js/JSON/p The syntax: ```js -let value = JSON.parse(str[, reviver]); +let value = JSON.parse(str, [reviver]); ``` str @@ -432,7 +432,7 @@ user = JSON.parse(user); alert( user.friends[1] ); // 1 ``` -The JSON may be as complex as necessary, objects and arrays can include other objects and arrays. But they must obey the format. +The JSON may be as complex as necessary, objects and arrays can include other objects and arrays. But they must obey the same JSON format. Here are typical mistakes in hand-written JSON (sometimes we have to write it for debugging purposes): @@ -481,7 +481,7 @@ Whoops! An error! The value of `meetup.date` is a string, not a `Date` object. How could `JSON.parse` know that it should transform that string into a `Date`? -Let's pass to `JSON.parse` the reviving function that returns all values "as is", but `date` will become a `Date`: +Let's pass to `JSON.parse` the reviving function as the second argument, that returns all values "as is", but `date` will become a `Date`: ```js run let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}'; diff --git a/1-js/05-data-types/12-json/json-meetup.svg b/1-js/05-data-types/12-json/json-meetup.svg new file mode 100644 index 000000000..5dbb4a9ab --- /dev/null +++ b/1-js/05-data-types/12-json/json-meetup.svg @@ -0,0 +1 @@ +number: 23title: "Conference"...placeoccupiedByparticipants \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.png b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.png deleted file mode 100644 index d0d37e35e..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.svg b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.svg new file mode 100644 index 000000000..224735b63 --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree.svg @@ -0,0 +1 @@ +fib ( 5 )fib(4)fib(3)fib(3)fib(2)fib(0)fib(1)fib(1)fib(2)fib(0)fib(1)fib(1)fib(2)fib(0)fib(1) \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree@2x.png b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree@2x.png deleted file mode 100644 index 3a937c64c..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/fibonacci-recursion-tree@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/solution.md b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/solution.md index 91bcecc05..36524a45a 100644 --- a/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/solution.md +++ b/1-js/06-advanced-functions/01-recursion/03-fibonacci-numbers/solution.md @@ -29,7 +29,7 @@ Here we can see that the value of `fib(3)` is needed for both `fib(5)` and `fib( Here's the full recursion tree: -![fibonacci recursion tree](fibonacci-recursion-tree.png) +![fibonacci recursion tree](fibonacci-recursion-tree.svg) We can clearly notice that `fib(3)` is evaluated two times and `fib(2)` is evaluated three times. The total amount of computations grows much faster than `n`, making it enormous even for `n=77`. diff --git a/1-js/06-advanced-functions/01-recursion/04-output-single-linked-list/solution.md b/1-js/06-advanced-functions/01-recursion/04-output-single-linked-list/solution.md index 4e9de1469..cfcbffea5 100644 --- a/1-js/06-advanced-functions/01-recursion/04-output-single-linked-list/solution.md +++ b/1-js/06-advanced-functions/01-recursion/04-output-single-linked-list/solution.md @@ -43,7 +43,7 @@ function printList(list) { } ``` -...But that would be unwise. In the future we may need to extend a function, do something else with the list. If we change `list`, then we loose such ability. +...But that would be unwise. In the future we may need to extend a function, do something else with the list. If we change `list`, then we lose such ability. Talking about good variable names, `list` here is the list itself. The first element of it. And it should remain like that. That's clear and reliable. diff --git a/1-js/06-advanced-functions/01-recursion/article.md b/1-js/06-advanced-functions/01-recursion/article.md index 214de18c2..9d2176536 100644 --- a/1-js/06-advanced-functions/01-recursion/article.md +++ b/1-js/06-advanced-functions/01-recursion/article.md @@ -70,7 +70,7 @@ pow(x, n) = We can also say that `pow` *recursively calls itself* till `n == 1`. -![recursive diagram of pow](recursion-pow.png) +![recursive diagram of pow](recursion-pow.svg) For example, to calculate `pow(2, 4)` the recursive variant does these steps: @@ -96,7 +96,7 @@ function pow(x, n) { The maximal number of nested calls (including the first one) is called *recursion depth*. In our case, it will be exactly `n`. -The maximal recursion depth is limited by JavaScript engine. We can make sure about 10000, some engines allow more, but 100000 is probably out of limit for the majority of them. There are automatic optimizations that help alleviate this ("tail calls optimizations"), but they are not yet supported everywhere and work only in simple cases. +The maximal recursion depth is limited by JavaScript engine. We can rely on it being 10000, some engines allow more, but 100000 is probably out of limit for the majority of them. There are automatic optimizations that help alleviate this ("tail calls optimizations"), but they are not yet supported everywhere and work only in simple cases. That limits the application of recursion, but it still remains very wide. There are many tasks where recursive way of thinking gives simpler code, easier to maintain. @@ -326,18 +326,18 @@ In other words, a company has departments. Now let's say we want a function to get the sum of all salaries. How can we do that? -An iterative approach is not easy, because the structure is not simple. The first idea may be to make a `for` loop over `company` with nested subloop over 1st level departments. But then we need more nested subloops to iterate over the staff in 2nd level departments like `sites`. ...And then another subloop inside those for 3rd level departments that might appear in the future? Should we stop on level 3 or make 4 levels of loops? If we put 3-4 nested subloops in the code to traverse a single object, it becomes rather ugly. +An iterative approach is not easy, because the structure is not simple. The first idea may be to make a `for` loop over `company` with nested subloop over 1st level departments. But then we need more nested subloops to iterate over the staff in 2nd level departments like `sites`... And then another subloop inside those for 3rd level departments that might appear in the future? If we put 3-4 nested subloops in the code to traverse a single object, it becomes rather ugly. Let's try recursion. As we can see, when our function gets a department to sum, there are two possible cases: -1. Either it's a "simple" department with an *array of people* -- then we can sum the salaries in a simple loop. -2. Or it's *an object with `N` subdepartments* -- then we can make `N` recursive calls to get the sum for each of the subdeps and combine the results. +1. Either it's a "simple" department with an *array* of people -- then we can sum the salaries in a simple loop. +2. Or it's *an object* with `N` subdepartments -- then we can make `N` recursive calls to get the sum for each of the subdeps and combine the results. -The (1) is the base of recursion, the trivial case. +The 1st case is the base of recursion, the trivial case, when we get an array. -The (2) is the recursive step. A complex task is split into subtasks for smaller departments. They may in turn split again, but sooner or later the split will finish at (1). +The 2nd case when we get an object is the recursive step. A complex task is split into subtasks for smaller departments. They may in turn split again, but sooner or later the split will finish at (1). The algorithm is probably even easier to read from the code: @@ -373,7 +373,7 @@ The code is short and easy to understand (hopefully?). That's the power of recur Here's the diagram of calls: -![recursive salaries](recursive-salaries.png) +![recursive salaries](recursive-salaries.svg) We can easily see the principle: for an object `{...}` subcalls are made, while arrays `[...]` are the "leaves" of the recursion tree, they give immediate result. @@ -444,7 +444,7 @@ let list = { Graphical representation of the list: -![linked list](linked-list.png) +![linked list](linked-list.svg) An alternative code for creation: @@ -464,7 +464,7 @@ let secondList = list.next.next; list.next.next = null; ``` -![linked list split](linked-list-split.png) +![linked list split](linked-list-split.svg) To join: @@ -488,7 +488,7 @@ list = { value: "new item", next: list }; */!* ``` -![linked list](linked-list-0.png) +![linked list](linked-list-0.svg) To remove a value from the middle, change `next` of the previous one: @@ -496,7 +496,7 @@ To remove a value from the middle, change `next` of the previous one: list.next = list.next.next; ``` -![linked list](linked-list-remove-1.png) +![linked list](linked-list-remove-1.svg) We made `list.next` jump over `1` to value `2`. The value `1` is now excluded from the chain. If it's not stored anywhere else, it will be automatically removed from the memory. diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-0.png b/1-js/06-advanced-functions/01-recursion/linked-list-0.png deleted file mode 100644 index c694e7021..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-0.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-0.svg b/1-js/06-advanced-functions/01-recursion/linked-list-0.svg new file mode 100644 index 000000000..f95e1bfca --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/linked-list-0.svg @@ -0,0 +1 @@ +value1nextvalue"new item"nextvalue2nextvalue3nextvalue4nextnulllist \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-0@2x.png b/1-js/06-advanced-functions/01-recursion/linked-list-0@2x.png deleted file mode 100644 index 1fe50ace4..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-0@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.png b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.png deleted file mode 100644 index b4c89ecdf..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg new file mode 100644 index 000000000..3828ec08c --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1.svg @@ -0,0 +1 @@ +value"new item"nextvalue1nextvalue2nextvalue3nextvalue4nextnulllist \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1@2x.png b/1-js/06-advanced-functions/01-recursion/linked-list-remove-1@2x.png deleted file mode 100644 index 6b5b95a0f..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-remove-1@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-split.png b/1-js/06-advanced-functions/01-recursion/linked-list-split.png deleted file mode 100644 index 310a36066..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-split.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-split.svg b/1-js/06-advanced-functions/01-recursion/linked-list-split.svg new file mode 100644 index 000000000..3db14be2f --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/linked-list-split.svg @@ -0,0 +1 @@ +value1nextvalue2nextvalue3nextvalue4nextnullnullsecondListlist \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/linked-list-split@2x.png b/1-js/06-advanced-functions/01-recursion/linked-list-split@2x.png deleted file mode 100644 index 2de39ca4f..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list-split@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list.png b/1-js/06-advanced-functions/01-recursion/linked-list.png deleted file mode 100644 index 80fabffc6..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/linked-list.svg b/1-js/06-advanced-functions/01-recursion/linked-list.svg new file mode 100644 index 000000000..6dd22939b --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/linked-list.svg @@ -0,0 +1 @@ +value1nextvalue2nextvalue3nextvalue4nextnulllist \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/linked-list@2x.png b/1-js/06-advanced-functions/01-recursion/linked-list@2x.png deleted file mode 100644 index 1e6dc1483..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/linked-list@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/recursion-pow.png b/1-js/06-advanced-functions/01-recursion/recursion-pow.png deleted file mode 100644 index 354f01271..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/recursion-pow.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/recursion-pow.svg b/1-js/06-advanced-functions/01-recursion/recursion-pow.svg new file mode 100644 index 000000000..8354cd150 --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/recursion-pow.svg @@ -0,0 +1 @@ +pow(x,n)xx * pow(x, n-1)n == 1 ?YesNorecursive call until n==1 \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/recursion-pow@2x.png b/1-js/06-advanced-functions/01-recursion/recursion-pow@2x.png deleted file mode 100644 index 22ae94410..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/recursion-pow@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/recursive-salaries.png b/1-js/06-advanced-functions/01-recursion/recursive-salaries.png deleted file mode 100644 index b40783a9b..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/recursive-salaries.png and /dev/null differ diff --git a/1-js/06-advanced-functions/01-recursion/recursive-salaries.svg b/1-js/06-advanced-functions/01-recursion/recursive-salaries.svg new file mode 100644 index 000000000..207271cbc --- /dev/null +++ b/1-js/06-advanced-functions/01-recursion/recursive-salaries.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/1-js/06-advanced-functions/01-recursion/recursive-salaries@2x.png b/1-js/06-advanced-functions/01-recursion/recursive-salaries@2x.png deleted file mode 100644 index e37597128..000000000 Binary files a/1-js/06-advanced-functions/01-recursion/recursive-salaries@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/02-rest-parameters-spread-operator/article.md b/1-js/06-advanced-functions/02-rest-parameters-spread-operator/article.md index a98d8eddd..2ade2c56b 100644 --- a/1-js/06-advanced-functions/02-rest-parameters-spread-operator/article.md +++ b/1-js/06-advanced-functions/02-rest-parameters-spread-operator/article.md @@ -8,7 +8,7 @@ For instance: - `Object.assign(dest, src1, ..., srcN)` -- copies properties from `src1..N` into `dest`. - ...and so on. -In this chapter we'll learn how to do the same. And, more importantly, how to feel comfortable working with such functions and arrays. +In this chapter we'll learn how to do the same. And also, how to pass arrays to such functions as parameters. ## Rest parameters `...` @@ -96,9 +96,7 @@ showName("Julius", "Caesar"); showName("Ilya"); ``` -In old times, rest parameters did not exist in the language, and using `arguments` was the only way to get all arguments of the function, no matter their total number. - -And it still works, we can use it today. +In old times, rest parameters did not exist in the language, and using `arguments` was the only way to get all arguments of the function. And it still works, we can find it in the old code. But the downside is that although `arguments` is both array-like and iterable, it's not an array. It does not support array methods, so we can't call `arguments.map(...)` for example. @@ -119,9 +117,10 @@ function f() { f(1); // 1 ``` -```` As we remember, arrow functions don't have their own `this`. Now we know they don't have the special `arguments` object either. +```` + ## Spread operator [#spread-operator] diff --git a/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.png b/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.png deleted file mode 100644 index 8e39564ff..000000000 Binary files a/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.svg b/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.svg new file mode 100644 index 000000000..5549a6a0f --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy.svg @@ -0,0 +1 @@ +outeri: 0i: 1i: 2i: 10...makeArmy() LexicalEnvironmentfor block LexicalEnvironment \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy@2x.png b/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy@2x.png deleted file mode 100644 index 39cc13a42..000000000 Binary files a/1-js/06-advanced-functions/03-closure/8-make-army/lexenv-makearmy@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/8-make-army/solution.md b/1-js/06-advanced-functions/03-closure/8-make-army/solution.md index f5afd4262..0fb0b4a49 100644 --- a/1-js/06-advanced-functions/03-closure/8-make-army/solution.md +++ b/1-js/06-advanced-functions/03-closure/8-make-army/solution.md @@ -84,7 +84,7 @@ Now it works correctly, because every time the code block in `for (let i=0...) { So, the value of `i` now lives a little bit closer. Not in `makeArmy()` Lexical Environment, but in the Lexical Environment that corresponds the current loop iteration. That's why now it works. -![](lexenv-makearmy.png) +![](lexenv-makearmy.svg) Here we rewrote `while` into `for`. diff --git a/1-js/06-advanced-functions/03-closure/article.md b/1-js/06-advanced-functions/03-closure/article.md index 6f175a775..a39dfc952 100644 --- a/1-js/06-advanced-functions/03-closure/article.md +++ b/1-js/06-advanced-functions/03-closure/article.md @@ -70,19 +70,19 @@ The Lexical Environment object consists of two parts: 1. *Environment Record* -- an object that stores all local variables as its properties (and some other information like the value of `this`). 2. A reference to the *outer lexical environment*, the one associated with the outer code. -**So, a "variable" is just a property of the special internal object, `Environment Record`. "To get or change a variable" means "to get or change a property of that object".** +**A "variable" is just a property of the special internal object, `Environment Record`. "To get or change a variable" means "to get or change a property of that object".** For instance, in this simple code, there is only one Lexical Environment: -![lexical environment](lexical-environment-global.png) +![lexical environment](lexical-environment-global.svg) This is a so-called global Lexical Environment, associated with the whole script. On the picture above, the rectangle means Environment Record (variable store) and the arrow means the outer reference. The global Lexical Environment has no outer reference, so it points to `null`. -Here's the bigger picture of what happens when a `let` changes: +And that's how it changes when a variable is defined and assigned: -![lexical environment](lexical-environment-global-2.png) +![lexical environment](lexical-environment-global-2.svg) Rectangles on the right-hand side demonstrate how the global Lexical Environment changes during the execution: @@ -110,7 +110,7 @@ That is why we can call a function declaration before it is defined. The code below demonstrates that the Lexical Environment is non-empty from the beginning. It has `say`, because that's a Function Declaration. And later it gets `phrase`, declared with `let`: -![lexical environment](lexical-environment-global-3.png) +![lexical environment](lexical-environment-global-3.svg) ### Inner and outer Lexical Environment @@ -119,7 +119,7 @@ Now let's go on and explore what happens when a function accesses an outer varia During the call, `say()` uses the outer variable `phrase`, let's look at the details of what's going on. -First, when a function runs, a new function Lexical Environment is created automatically. That's a general rule for all functions. That Lexical Environment is used to store local variables and parameters of the call. +When a function runs, a new Lexical Environment is created automatically to store local variables and parameters of the call. For instance, for `say("John")`, it looks like this (the execution is at the line, labelled with an arrow): @@ -134,7 +134,7 @@ For instance, for `say("John")`, it looks like this (the execution is at the lin say("John"); // Hello, John ```--> -![lexical environment](lexical-environment-simple.png) +![lexical environment](lexical-environment-simple.svg) So, during the function call we have two Lexical Environments: the inner one (for the function call) and the outer one (global): @@ -143,26 +143,26 @@ So, during the function call we have two Lexical Environments: the inner one (fo It has a single property: `name`, the function argument. We called `say("John")`, so the value of `name` is `"John"`. - The outer Lexical Environment is the global Lexical Environment. - It has `phrase` and the function itself. + It has `phrase` variable and the function itself. -The inner Lexical Environment has a reference to the outer one. +The inner Lexical Environment has a reference to the `outer` one. **When the code wants to access a variable -- the inner Lexical Environment is searched first, then the outer one, then the more outer one and so on until the global one.** -If a variable is not found anywhere, that's an error in strict mode. Without `use strict`, an assignment to an undefined variable creates a new global variable, for backwards compatibility. +If a variable is not found anywhere, that's an error in strict mode (without `use strict`, an assignment to a non-existing variable, like `user = "John"` creates a new global variable `user`, that's for backwards compatibility). Let's see how the search proceeds in our example: - When the `alert` inside `say` wants to access `name`, it finds it immediately in the function Lexical Environment. - When it wants to access `phrase`, then there is no `phrase` locally, so it follows the reference to the enclosing Lexical Environment and finds it there. -![lexical environment lookup](lexical-environment-simple-lookup.png) +![lexical environment lookup](lexical-environment-simple-lookup.svg) Now we can give the answer to the first question from the beginning of the chapter. -**A function gets outer variables as they are now; it uses the most recent values.** +**A function gets outer variables as they are now, it uses the most recent values.** -That's because of the described mechanism. Old variable values are not saved anywhere. When a function wants them, it takes the current values from its own or an outer Lexical Environment. +Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one. So the answer to the first question is `Pete`: @@ -195,7 +195,7 @@ And if a function is called multiple times, then each invocation will have its o ``` ```smart header="Lexical Environment is a specification object" -"Lexical Environment" is a specification object. We can't get this object in our code and manipulate it directly. JavaScript engines also may optimize it, discard variables that are unused to save memory and perform other internal tricks, but the visible behavior should be as described. +"Lexical Environment" is a specification object: it only exists "theoretically" in the [language specification](https://tc39.es/ecma262/#sec-lexical-environments) to describe how things work. We can't get this object in our code and manipulate it directly. JavaScript engines also may optimize it, discard variables that are unused to save memory and perform other internal tricks, as long as the visible behavior remains as described. ``` @@ -265,7 +265,7 @@ How does the counter work internally? When the inner function runs, the variable in `count++` is searched from inside out. For the example above, the order will be: -![](lexical-search-order.png) +![](lexical-search-order.svg) 1. The locals of the nested function... 2. The variables of the outer function... @@ -309,35 +309,37 @@ alert( counter2() ); // 0 (independent) ``` -Hopefully, the situation with outer variables is clear now. For most situations such understanding is enough. There are few details in the specification that we omitted for brevity. So in the next section we cover even more details, not to miss anything. +Hopefully, the situation with outer variables is clear now. For most situations such understanding is enough. There are few details in the specification that we omitted for brevity. So in the next section we cover even more details. ## Environments in detail -Here's what's going on in the `makeCounter` example step-by-step, follow it to make sure that you know things in the very detail. +Here's what's going on in the `makeCounter` example step-by-step, follow it to make sure that you understand how it works in detail. Please note the additional `[[Environment]]` property is covered here. We didn't mention it before for simplicity. 1. When the script has just started, there is only global Lexical Environment: - ![](lexenv-nested-makecounter-1.png) + ![](lexenv-nested-makecounter-1.svg) At that starting moment there is only `makeCounter` function, because it's a Function Declaration. It did not run yet. - **All functions "on birth" receive a hidden property `[[Environment]]` with a reference to the Lexical Environment of their creation.** We didn't talk about it yet, but that's how the function knows where it was made. + **All functions "on birth" receive a hidden property `[[Environment]]` with a reference to the Lexical Environment of their creation.** + + We didn't talk about it yet, that's how the function knows where it was made. Here, `makeCounter` is created in the global Lexical Environment, so `[[Environment]]` keeps a reference to it. In other words, a function is "imprinted" with a reference to the Lexical Environment where it was born. And `[[Environment]]` is the hidden function property that has that reference. -2. The code runs on, the new global variable `counter` is declared and for its value `makeCounter()` is called. Here's a snapshot of the moment when the execution is on the first line inside `makeCounter()`: +2. The code runs on, the new global variable `counter` is declared and gets the result of `makeCounter()` call. Here's a snapshot of the moment when the execution is on the first line inside `makeCounter()`: - ![](lexenv-nested-makecounter-2.png) + ![](lexenv-nested-makecounter-2.svg) At the moment of the call of `makeCounter()`, the Lexical Environment is created, to hold its variables and arguments. As all Lexical Environments, it stores two things: 1. An Environment Record with local variables. In our case `count` is the only local variable (appearing when the line with `let count` is executed). - 2. The outer lexical reference, which is set to `[[Environment]]` of the function. Here `[[Environment]]` of `makeCounter` references the global Lexical Environment. + 2. The outer lexical reference, which is set to the value of `[[Environment]]` of the function. Here `[[Environment]]` of `makeCounter` references the global Lexical Environment. So, now we have two Lexical Environments: the first one is global, the second one is for the current `makeCounter` call, with the outer reference to global. @@ -347,23 +349,21 @@ Please note the additional `[[Environment]]` property is covered here. We didn't For our new nested function the value of `[[Environment]]` is the current Lexical Environment of `makeCounter()` (where it was born): - ![](lexenv-nested-makecounter-3.png) + ![](lexenv-nested-makecounter-3.svg) Please note that on this step the inner function was created, but not yet called. The code inside `function() { return count++; }` is not running. 4. As the execution goes on, the call to `makeCounter()` finishes, and the result (the tiny nested function) is assigned to the global variable `counter`: - ![](lexenv-nested-makecounter-4.png) + ![](lexenv-nested-makecounter-4.svg) That function has only one line: `return count++`, that will be executed when we run it. -5. When the `counter()` is called, an "empty" Lexical Environment is created for it. It has no local variables by itself. But the `[[Environment]]` of `counter` is used as the outer reference for it, so it has access to the variables of the former `makeCounter()` call where it was created: - - ![](lexenv-nested-makecounter-5.png) +5. When `counter()` is called, a new Lexical Environment is created for the call. It's empty, as `counter` has no local variables by itself. But the `[[Environment]]` of `counter` is used as the `outer` reference for it, that provides access to the variables of the former `makeCounter()` call where it was created: - Now if it accesses a variable, it first searches its own Lexical Environment (empty), then the Lexical Environment of the former `makeCounter()` call, then the global one. + ![](lexenv-nested-makecounter-5.svg) - When it looks for `count`, it finds it among the variables `makeCounter`, in the nearest outer Lexical Environment. + Now when the call looks for `count` variable, it first searches its own Lexical Environment (empty), then the Lexical Environment of the outer `makeCounter()` call, where finds it. Please note how memory management works here. Although `makeCounter()` call finished some time ago, its Lexical Environment was retained in memory, because there's a nested function with `[[Environment]]` referencing it. @@ -371,17 +371,15 @@ Please note the additional `[[Environment]]` property is covered here. We didn't 6. The call to `counter()` not only returns the value of `count`, but also increases it. Note that the modification is done "in place". The value of `count` is modified exactly in the environment where it was found. - ![](lexenv-nested-makecounter-6.png) - - So we return to the previous step with the only change -- the new value of `count`. The following calls all do the same. + ![](lexenv-nested-makecounter-6.svg) 7. Next `counter()` invocations do the same. The answer to the second question from the beginning of the chapter should now be obvious. -The `work()` function in the code below uses the `name` from the place of its origin through the outer lexical environment reference: +The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference: -![](lexenv-nested-work.png) +![](lexenv-nested-work.svg) So, the result is `"Pete"` here. @@ -420,7 +418,7 @@ In the example below, the `user` variable exists only in the `if` block: alert(user); // Error, can't see such variable! ```--> -![](lexenv-if.png) +![](lexenv-if.svg) When the execution gets into the `if` block, the new "if-only" Lexical Environment is created for it. @@ -430,7 +428,7 @@ For instance, after `if` finishes, the `alert` below won't see the `user`, hence ### For, while -For a loop, every iteration has a separate Lexical Environment. If a variable is declared in `for`, then it's also local to that Lexical Environment: +For a loop, every iteration has a separate Lexical Environment. If a variable is declared in `for(let ...)`, then it's also in there: ```js run for (let i = 0; i < 10; i++) { @@ -441,7 +439,7 @@ for (let i = 0; i < 10; i++) { alert(i); // Error, no such variable ``` -Please note: `let i` is visually outside of `{...}`. The `for` construct is somewhat special here: each iteration of the loop has its own Lexical Environment with the current `i` in it. +Please note: `let i` is visually outside of `{...}`. The `for` construct is special here: each iteration of the loop has its own Lexical Environment with the current `i` in it. Again, similarly to `if`, after the loop `i` is not visible. @@ -537,7 +535,7 @@ There exist other ways besides parentheses to tell JavaScript that we mean a Fun }(); ``` -In all the above cases we declare a Function Expression and run it immediately. +In all the above cases we declare a Function Expression and run it immediately. Let's note again: nowadays there's no reason to write such code. ## Garbage collection @@ -554,7 +552,7 @@ f(); Here two values are technically the properties of the Lexical Environment. But after `f()` finishes that Lexical Environment becomes unreachable, so it's deleted from the memory. -...But if there's a nested function that is still reachable after the end of `f`, then its `[[Environment]]` reference keeps the outer lexical environment alive as well: +...But if there's a nested function that is still reachable after the end of `f`, then it has `[[Environment]]` property that references the outer lexical environment, so it's also reachable and alive: ```js function f() { @@ -570,7 +568,7 @@ function f() { let g = f(); // g is reachable, and keeps the outer lexical environment in memory ``` -Please note that if `f()` is called many times, and resulting functions are saved, then the corresponding Lexical Environment objects will also be retained in memory. All 3 of them in the code below: +Please note that if `f()` is called many times, and resulting functions are saved, then all corresponding Lexical Environment objects will also be retained in memory. All 3 of them in the code below: ```js function f() { @@ -579,9 +577,8 @@ function f() { return function() { alert(value); }; } -// 3 functions in array, every one of them links to Lexical Environment (LE for short) +// 3 functions in array, every one of them links to Lexical Environment // from the corresponding f() run -// LE LE LE let arr = [f(), f(), f()]; ``` @@ -599,7 +596,7 @@ function f() { } let g = f(); // while g is alive -// there corresponding Lexical Environment lives +// their corresponding Lexical Environment lives g = null; // ...and now the memory is cleaned up ``` @@ -608,7 +605,7 @@ g = null; // ...and now the memory is cleaned up As we've seen, in theory while a function is alive, all outer variables are also retained. -But in practice, JavaScript engines try to optimize that. They analyze variable usage and if it's easy to see that an outer variable is not used -- it is removed. +But in practice, JavaScript engines try to optimize that. They analyze variable usage and if it's obvious from the code that an outer variable is not used -- it is removed. **An important side effect in V8 (Chrome, Opera) is that such variable will become unavailable in debugging.** @@ -621,7 +618,7 @@ function f() { let value = Math.random(); function g() { - debugger; // in console: type alert( value ); No such variable! + debugger; // in console: type alert(value); No such variable! } return g; @@ -642,7 +639,7 @@ function f() { let value = "the closest value"; function g() { - debugger; // in console: type alert( value ); Surprise! + debugger; // in console: type alert(value); Surprise! } return g; diff --git a/1-js/06-advanced-functions/03-closure/lexenv-if.png b/1-js/06-advanced-functions/03-closure/lexenv-if.png deleted file mode 100644 index 5a11b65de..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-if.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-if.svg b/1-js/06-advanced-functions/03-closure/lexenv-if.svg new file mode 100644 index 000000000..e2b8d6f69 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-if.svg @@ -0,0 +1 @@ +phrase: "Hello"outerouternulluser: "John" \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-if@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-if@2x.png deleted file mode 100644 index 794676cda..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-if@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.png deleted file mode 100644 index c6083a452..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.svg new file mode 100644 index 000000000..70649ffd5 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1.svg @@ -0,0 +1 @@ +makeCounter: function[[Environment]]outernull \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1@2x.png deleted file mode 100644 index af57c51cd..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-1@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.png deleted file mode 100644 index dce67876f..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg new file mode 100644 index 000000000..b6a8bd486 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2.svg @@ -0,0 +1 @@ +makeCounter: functioncounter: undefinedcount: 0outerouternullglobal LexicalEnvironmentLexicalEnvironment of makeCounter() call \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2@2x.png deleted file mode 100644 index 9bba88bc5..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-2@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.png deleted file mode 100644 index 4d5a787c2..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.svg new file mode 100644 index 000000000..aa0eee4e3 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3.svg @@ -0,0 +1 @@ +makeCounter: functioncounter: undefinedcount: 0outerouternull[[Environment]] \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3@2x.png deleted file mode 100644 index c7575f4d5..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-3@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.png deleted file mode 100644 index 70b4a09bf..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.svg new file mode 100644 index 000000000..216658f59 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4.svg @@ -0,0 +1 @@ +makeCounter: functioncounter: functioncount: 0outerouternull[[Environment]] \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4@2x.png deleted file mode 100644 index 4cc762c10..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-4@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.png deleted file mode 100644 index 7410dddc8..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.svg new file mode 100644 index 000000000..eff2c7dd9 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5.svg @@ -0,0 +1 @@ +makeCounter: functioncounter: functioncount: 0<empty>outerouterouternull[[Environment]] \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5@2x.png deleted file mode 100644 index 103c66fb5..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-5@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.png deleted file mode 100644 index 44366ed78..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg new file mode 100644 index 000000000..4eb3a6e38 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6.svg @@ -0,0 +1 @@ +makeCounter: functioncounter: functioncount: 1outerouternull[[Environment]]modified here \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6@2x.png deleted file mode 100644 index 36df7cadd..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-makecounter-6@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-work.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-work.png deleted file mode 100644 index 3bdf5108d..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-work.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-work.svg b/1-js/06-advanced-functions/03-closure/lexenv-nested-work.svg new file mode 100644 index 000000000..ae115aa23 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexenv-nested-work.svg @@ -0,0 +1 @@ +makeWorker: function name: "John"<empty>outerouterouternullname: "Pete" \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexenv-nested-work@2x.png b/1-js/06-advanced-functions/03-closure/lexenv-nested-work@2x.png deleted file mode 100644 index 023dba05c..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexenv-nested-work@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.png deleted file mode 100644 index 342bdae98..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg new file mode 100644 index 000000000..f077d5a88 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2.svg @@ -0,0 +1 @@ +phrase: "Bye"phrase: "Hello"phrase: undefined<empty>outernullexecution start \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2@2x.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global-2@2x.png deleted file mode 100644 index 55306e666..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global-2@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.png deleted file mode 100644 index 1cd77f8ac..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg new file mode 100644 index 000000000..4eaa7de74 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3.svg @@ -0,0 +1 @@ +say: function phrase: "Hello"say: functionouternullexecution start \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3@2x.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global-3@2x.png deleted file mode 100644 index 3e256bbb9..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global-3@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global.png deleted file mode 100644 index 6899a777f..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-global.svg new file mode 100644 index 000000000..f974122ff --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-environment-global.svg @@ -0,0 +1 @@ +phrase: "Hello"outernullLexicalEnvironment \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-global@2x.png b/1-js/06-advanced-functions/03-closure/lexical-environment-global@2x.png deleted file mode 100644 index 91980cf84..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-global@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.png b/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.png deleted file mode 100644 index 56aafaf3d..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.svg new file mode 100644 index 000000000..242f970eb --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup.svg @@ -0,0 +1 @@ +say: function phrase: "Hello"name: "John"outerouternull \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup@2x.png b/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup@2x.png deleted file mode 100644 index f423b125e..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-simple-lookup@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple.png b/1-js/06-advanced-functions/03-closure/lexical-environment-simple.png deleted file mode 100644 index 2424fbf23..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-simple.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple.svg b/1-js/06-advanced-functions/03-closure/lexical-environment-simple.svg new file mode 100644 index 000000000..c351f9d71 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-environment-simple.svg @@ -0,0 +1 @@ +say: function phrase: "Hello"name: "John"outerouternullLexicalEnvironment for the call \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-environment-simple@2x.png b/1-js/06-advanced-functions/03-closure/lexical-environment-simple@2x.png deleted file mode 100644 index b206cbe8b..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-environment-simple@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-search-order.png b/1-js/06-advanced-functions/03-closure/lexical-search-order.png deleted file mode 100644 index 1b641d48d..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-search-order.png and /dev/null differ diff --git a/1-js/06-advanced-functions/03-closure/lexical-search-order.svg b/1-js/06-advanced-functions/03-closure/lexical-search-order.svg new file mode 100644 index 000000000..4b960daa9 --- /dev/null +++ b/1-js/06-advanced-functions/03-closure/lexical-search-order.svg @@ -0,0 +1 @@ +123 \ No newline at end of file diff --git a/1-js/06-advanced-functions/03-closure/lexical-search-order@2x.png b/1-js/06-advanced-functions/03-closure/lexical-search-order@2x.png deleted file mode 100644 index f06bc3ed8..000000000 Binary files a/1-js/06-advanced-functions/03-closure/lexical-search-order@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/04-var/article.md b/1-js/06-advanced-functions/04-var/article.md index 487f9e29e..02fd43fe5 100644 --- a/1-js/06-advanced-functions/04-var/article.md +++ b/1-js/06-advanced-functions/04-var/article.md @@ -31,7 +31,7 @@ alert(phrase); // Error, phrase is not defined ## "var" has no block scope -`var` variables are either function-wide or global, they are visible through blocks. +Variables, declared with `var`, are either function-wide or global. They are visible through blocks. For instance: @@ -45,7 +45,7 @@ alert(test); // true, the variable lives after if */!* ``` -`var` ignores code blocks, so we've got a global variable `test`. +As `var` ignores code blocks, we've got a global variable `test`. If we used `let test` instead of `var test`, then the variable would only be visible inside `if`: diff --git a/1-js/06-advanced-functions/05-global-object/article.md b/1-js/06-advanced-functions/05-global-object/article.md index 5892f0798..3d195a978 100644 --- a/1-js/06-advanced-functions/05-global-object/article.md +++ b/1-js/06-advanced-functions/05-global-object/article.md @@ -1,22 +1,23 @@ # Global object -The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the environment. +The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment. In a browser it is named `window`, for Node.js it is `global`, for other environments it may have another name. -Recently, `globalThis` was added to the language, as a standartized name for a global object, that should be supported across all environments. In some browsers, namely non-Chromium Edge, `globalThis` is not yet supported, but can be easily polyfilled. +Recently, `globalThis` was added to the language, as a standardized name for a global object, that should be supported across all environments. In some browsers, namely non-Chromium Edge, `globalThis` is not yet supported, but can be easily polyfilled. + +We'll use `window` here, assuming that our environment is a browser. If your script may run in other environments, it's better to use `globalThis` instead. All properties of the global object can be accessed directly: ```js run alert("Hello"); - -// the same as +// is the same as window.alert("Hello"); ``` -In a browser, global functions and variables declared with `var` become the property of the global object: +In a browser, global functions and variables declared with `var` (not `let/const`!) become the property of the global object: ```js run untrusted refresh var gVar = 5; @@ -24,9 +25,9 @@ var gVar = 5; alert(window.gVar); // 5 (became a property of the global object) ``` -Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use JavaScript modules where such thing doesn't happen. We'll cover them later in the chapter [](info:modules). +Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use [JavaScript modules](info:modules) where such thing doesn't happen. -Also, more modern variable declarations `let` and `const` do not exhibit such behavior at all: +If we used `let` instead, such thing wouldn't happen: ```js run untrusted refresh let gLet = 5; @@ -52,7 +53,7 @@ alert(currentUser.name); // John alert(window.currentUser.name); // John ``` -That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets "input" variables and produces certain "outcome" is clearer, less prone to errors and easier to test. +That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets "input" variables and produces certain "outcome" is clearer, less prone to errors and easier to test than if it uses outer or global variables. ## Using for polyfills diff --git a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md index 0177c8f6e..a11821d67 100644 --- a/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md +++ b/1-js/06-advanced-functions/06-function-object/2-counter-inc-dec/task.md @@ -7,8 +7,8 @@ importance: 5 Modify the code of `makeCounter()` so that the counter can also decrease and set the number: - `counter()` should return the next number (as before). -- `counter.set(value)` should set the `count` to `value`. -- `counter.decrease()` should decrease the `count` by 1. +- `counter.set(value)` should set the counter to `value`. +- `counter.decrease()` should decrease the counter by 1. See the sandbox code for the complete usage example. diff --git a/1-js/06-advanced-functions/06-function-object/article.md b/1-js/06-advanced-functions/06-function-object/article.md index e907086c2..2b4a7ac8c 100644 --- a/1-js/06-advanced-functions/06-function-object/article.md +++ b/1-js/06-advanced-functions/06-function-object/article.md @@ -1,7 +1,7 @@ # Function object, NFE -As we already know, functions in JavaScript are values. +As we already know, a function in JavaScript is a value. Every value in JavaScript has a type. What type is a function? @@ -12,7 +12,7 @@ A good way to imagine functions is as callable "action objects". We can not only ## The "name" property -Function objects contain a few useable properties. +Function objects contain some useable properties. For instance, a function's name is accessible as the "name" property: @@ -24,14 +24,14 @@ function sayHi() { alert(sayHi.name); // sayHi ``` -What's more funny, the name-assigning logic is smart. It also assigns the correct name to functions that are used in assignments: +What's kind of funny, the name-assigning logic is smart. It also assigns the correct name to a function even if it's created without one, and then immediately assigned: ```js run let sayHi = function() { alert("Hi"); -} +}; -alert(sayHi.name); // sayHi (works!) +alert(sayHi.name); // sayHi (there's a name!) ``` It also works if the assignment is done via a default value: @@ -93,7 +93,7 @@ alert(many.length); // 2 Here we can see that rest parameters are not counted. -The `length` property is sometimes used for introspection in functions that operate on other functions. +The `length` property is sometimes used for [introspection](https://en.wikipedia.org/wiki/Type_introspection) in functions that operate on other functions. For instance, in the code below the `ask` function accepts a `question` to ask and an arbitrary number of `handler` functions to call. @@ -102,9 +102,9 @@ Once a user provides their answer, the function calls the handlers. We can pass - A zero-argument function, which is only called when the user gives a positive answer. - A function with arguments, which is called in either case and returns an answer. -The idea is that we have a simple, no-arguments handler syntax for positive cases (most frequent variant), but are able to provide universal handlers as well. +To call `handler` the right way, we examine the `handler.length` property. -To call `handlers` the right way, we examine the `length` property: +The idea is that we have a simple, no-arguments handler syntax for positive cases (most frequent variant), but are able to support universal handlers as well: ```js run function ask(question, ...handlers) { @@ -241,7 +241,7 @@ let sayHi = function *!*func*/!*(who) { sayHi("John"); // Hello, John ``` -There are two special things about the name `func`: +There are two special things about the name `func`, that are the reasons for it: 1. It allows the function to reference itself internally. 2. It is not visible outside of the function. @@ -282,7 +282,7 @@ let sayHi = function(who) { }; ``` -The problem with that code is that the value of `sayHi` may change. The function may go to another variable, and the code will start to give errors: +The problem with that code is that `sayHi` may change in the outer code. If the function gets assigned to another variable instead, the code will start to give errors: ```js run let sayHi = function(who) { @@ -347,6 +347,7 @@ If the function is declared as a Function Expression (not in the main code flow) Also, functions may carry additional properties. Many well-known JavaScript libraries make great use of this feature. -They create a "main" function and attach many other "helper" functions to it. For instance, the [jquery](https://jquery.com) library creates a function named `$`. The [lodash](https://lodash.com) library creates a function `_`. And then adds `_.clone`, `_.keyBy` and other properties to (see the [docs](https://lodash.com/docs) when you want learn more about them). Actually, they do it to lessen their pollution of the global space, so that a single library gives only one global variable. That reduces the possibility of naming conflicts. +They create a "main" function and attach many other "helper" functions to it. For instance, the [jQuery](https://jquery.com) library creates a function named `$`. The [lodash](https://lodash.com) library creates a function `_`, and then adds `_.clone`, `_.keyBy` and other properties to it (see the [docs](https://lodash.com/docs) when you want learn more about them). Actually, they do it to lessen their pollution of the global space, so that a single library gives only one global variable. That reduces the possibility of naming conflicts. + So, a function can do a useful job by itself and also carry a bunch of other functionality in properties. diff --git a/1-js/06-advanced-functions/07-new-function/article.md b/1-js/06-advanced-functions/07-new-function/article.md index b36b68af0..3214ba376 100644 --- a/1-js/06-advanced-functions/07-new-function/article.md +++ b/1-js/06-advanced-functions/07-new-function/article.md @@ -46,14 +46,13 @@ It is used in very specific cases, like when we receive code from a server, or t ## Closure -Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created. +Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created (we covered that in the chapter ). -But when a function is created using `new Function`, its `[[Environment]]` references not the current Lexical Environment, but instead the global one. +But when a function is created using `new Function`, its `[[Environment]]` is set to reference not the current Lexical Environment, but the global one. So, such function doesn't have access to outer variables, only to the global ones. ```js run - function getFunc() { let value = "test"; @@ -99,6 +98,8 @@ So if `new Function` had access to outer variables, it would be unable to find r **If `new Function` had access to outer variables, it would have problems with minifiers.** +Besides, such code would be architecturally bad and prone to errors. + To pass something to a function, created as `new Function`, we should use its arguments. ## Summary @@ -111,7 +112,7 @@ let func = new Function ([arg1, arg2, ...argN], functionBody); For historical reasons, arguments can also be given as a comma-separated list. -These three lines mean the same: +These three declarations mean the same: ```js new Function('a', 'b', 'return a + b'); // basic syntax @@ -119,4 +120,4 @@ new Function('a,b', 'return a + b'); // comma-separated new Function('a , b', 'return a + b'); // comma-separated with spaces ``` -Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it saves us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers. +Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers. diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/solution.md b/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/solution.md deleted file mode 100644 index 735a446f7..000000000 --- a/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/solution.md +++ /dev/null @@ -1,22 +0,0 @@ - - -```js run -let i = 0; - -let start = Date.now(); - -let timer = setInterval(count); - -function count() { - - for(let j = 0; j < 1000000; j++) { - i++; - } - - if (i == 1000000000) { - alert("Done in " + (Date.now() - start) + 'ms'); - clearInterval(timer); - } - -} -``` diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/task.md b/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/task.md deleted file mode 100644 index c3455c2a1..000000000 --- a/1-js/06-advanced-functions/08-settimeout-setinterval/3-rewrite-settimeout/task.md +++ /dev/null @@ -1,32 +0,0 @@ -importance: 4 - ---- - -# Rewrite setTimeout with setInterval - -Here's the function that uses nested `setTimeout` to split a job into pieces. - -Rewrite it to `setInterval`: - -```js run -let i = 0; - -let start = Date.now(); - -function count() { - - if (i == 1000000000) { - alert("Done in " + (Date.now() - start) + 'ms'); - } else { - setTimeout(count); - } - - // a piece of heavy job - for(let j = 0; j < 1000000; j++) { - i++; - } - -} - -count(); -``` diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/article.md b/1-js/06-advanced-functions/08-settimeout-setinterval/article.md index 2ff7d6dcd..e55e779a9 100644 --- a/1-js/06-advanced-functions/08-settimeout-setinterval/article.md +++ b/1-js/06-advanced-functions/08-settimeout-setinterval/article.md @@ -9,7 +9,6 @@ There are two methods for it: These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js. - ## setTimeout The syntax: @@ -75,7 +74,7 @@ Novice developers sometimes make a mistake by adding brackets `()` after the fun // wrong! setTimeout(sayHi(), 1000); ``` -That doesn't work, because `setTimeout` expects a reference to function. And here `sayHi()` runs the function, and the *result of its execution* is passed to `setTimeout`. In our case the result of `sayHi()` is `undefined` (the function returns nothing), so nothing is scheduled. +That doesn't work, because `setTimeout` expects a reference to a function. And here `sayHi()` runs the function, and the *result of its execution* is passed to `setTimeout`. In our case the result of `sayHi()` is `undefined` (the function returns nothing), so nothing is scheduled. ```` ### Canceling with clearTimeout @@ -130,7 +129,7 @@ setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000); ```smart header="Time goes on while `alert` is shown" In most browsers, including Chrome and Firefox the internal timer continues "ticking" while showing `alert/confirm/prompt`. -So if you run the code above and don't dismiss the `alert` window for some time, then in the next `alert` will be shown immediately as you do it. The actual interval between alerts will be shorter than 5 seconds. +So if you run the code above and don't dismiss the `alert` window for some time, then in the next `alert` will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds. ``` ## Recursive setTimeout @@ -176,9 +175,9 @@ let timerId = setTimeout(function request() { ``` -And if we the functions that we're scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later. +And if the functions that we're scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later. -**Recursive `setTimeout` guarantees a delay between the executions, `setInterval` -- does not.** +**Recursive `setTimeout` allows to set the delay between the executions more precisely than `setInterval`.** Let's compare two code fragments. The first one uses `setInterval`: @@ -201,7 +200,7 @@ setTimeout(function run() { For `setInterval` the internal scheduler will run `func(i)` every 100ms: -![](setinterval-interval.png) +![](setinterval-interval.svg) Did you notice? @@ -217,13 +216,13 @@ In the edge case, if the function always executes longer than `delay` ms, then t And here is the picture for the recursive `setTimeout`: -![](settimeout-interval.png) +![](settimeout-interval.svg) **The recursive `setTimeout` guarantees the fixed delay (here 100ms).** That's because a new call is planned at the end of the previous one. -````smart header="Garbage collection" +````smart header="Garbage collection and setInterval/setTimeout callback" When a function is passed in `setInterval/setTimeout`, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it. ```js @@ -236,13 +235,13 @@ For `setInterval` the function stays in memory until `clearInterval` is called. There's a side-effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So when we don't need the scheduled function anymore, it's better to cancel it, even if it's very small. ```` -## setTimeout(...,0) +## Zero delay setTimeout There's a special use case: `setTimeout(func, 0)`, or just `setTimeout(func)`. This schedules the execution of `func` as soon as possible. But scheduler will invoke it only after the current code is complete. -So the function is scheduled to run "right after" the current code. In other words, *asynchronously*. +So the function is scheduled to run "right after" the current code. For instance, this outputs "Hello", then immediately "World": @@ -254,114 +253,12 @@ alert("Hello"); The first line "puts the call into calendar after 0ms". But the scheduler will only "check the calendar" after the current code is complete, so `"Hello"` is first, and `"World"` -- after it. -### Splitting CPU-hungry tasks - -There's a trick to split CPU-hungry tasks using `setTimeout`. - -For instance, a syntax-highlighting script (used to colorize code examples on this page) is quite CPU-heavy. To highlight the code, it performs the analysis, creates many colored elements, adds them to the document -- for a big text that takes a lot. It may even cause the browser to "hang", which is unacceptable. - -So we can split the long text into pieces. First 100 lines, then plan another 100 lines using `setTimeout(..., 0)`, and so on. - -For clarity, let's take a simpler example for consideration. We have a function to count from `1` to `1000000000`. - -If you run it, the CPU will hang. For server-side JS that's clearly noticeable, and if you are running it in-browser, then try to click other buttons on the page -- you'll see that whole JavaScript actually is paused, no other actions work until it finishes. - -```js run -let i = 0; - -let start = Date.now(); - -function count() { - - // do a heavy job - for (let j = 0; j < 1e9; j++) { - i++; - } - - alert("Done in " + (Date.now() - start) + 'ms'); -} - -count(); -``` - -The browser may even show "the script takes too long" warning (but hopefully it won't, because the number is not very big). - -Let's split the job using the nested `setTimeout`: - -```js run -let i = 0; - -let start = Date.now(); - -function count() { - - // do a piece of the heavy job (*) - do { - i++; - } while (i % 1e6 != 0); - - if (i == 1e9) { - alert("Done in " + (Date.now() - start) + 'ms'); - } else { - setTimeout(count); // schedule the new call (**) - } - -} - -count(); -``` - -Now the browser UI is fully functional during the "counting" process. - -We do a part of the job `(*)`: - -1. First run: `i=1...1000000`. -2. Second run: `i=1000001..2000000`. -3. ...and so on, the `while` checks if `i` is evenly divided by `1000000`. - -Then the next call is scheduled in `(**)` if we're not done yet. - -Pauses between `count` executions provide just enough "breath" for the JavaScript engine to do something else, to react to other user actions. - -The notable thing is that both variants -- with and without splitting the job by `setTimeout` -- are comparable in speed. There's no much difference in the overall counting time. - -To make them closer, let's make an improvement. - -We'll move the scheduling in the beginning of the `count()`: +There are also advanced browser-related use cases of zero-delay timeout, that we'll discuss in the chapter . -```js run -let i = 0; - -let start = Date.now(); - -function count() { - - // move the scheduling at the beginning - if (i < 1e9 - 1e6) { - setTimeout(count); // schedule the new call - } - - do { - i++; - } while (i % 1e6 != 0); - - if (i == 1e9) { - alert("Done in " + (Date.now() - start) + 'ms'); - } - -} - -count(); -``` - -Now when we start to `count()` and see that we'll need to `count()` more, we schedule that immediately, before doing the job. - -If you run it, it's easy to notice that it takes significantly less time. +````smart header="Zero delay is in fact not zero (in a browser)" +In the browser, there's a limitation of how often nested timers can run. The [HTML5 standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) says: "after five nested timers, the interval is forced to be at least 4 milliseconds.". -````smart header="Minimal delay of nested timers in-browser" -In the browser, there's a limitation of how often nested timers can run. The [HTML5 standard](https://www.w3.org/TR/html5/webappapis.html#timers) says: "after five nested timers, the interval is forced to be at least four milliseconds.". - -Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself after `0ms`. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see: +Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see: ```js run let start = Date.now(); @@ -378,85 +275,28 @@ setTimeout(function run() { // 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100 ``` -First timers run immediately (just as written in the spec), and then the delay comes into play and we see `9, 15, 20, 24...`. +First timers run immediately (just as written in the spec), and then we see `9, 15, 20, 24...`. The 4+ ms obligatory delay between invocations comes into play. + +The similar thing happens if we use `setInterval` instead of `setTimeout`: `setInterval(f)` runs `f` few times with zero-delay, and afterwards with 4+ ms delay. That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons. -For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like [process.nextTick](https://nodejs.org/api/process.html) and [setImmediate](https://nodejs.org/api/timers.html) for Node.js. So the notion is browser-specific only. +For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like [setImmediate](https://nodejs.org/api/timers.html) for Node.js. So this note is browser-specific. ```` -### Allowing the browser to render - -Another benefit of splitting heavy tasks for browser scripts is that we can show a progress bar or something to the user. - -Usually the browser does all "repainting" after the currently running code is complete. So if we do a single huge function that changes many elements, the changes are not painted out till it finishes. - -Here's the demo: -```html run -
- - -``` - -If you run it, the changes to `i` will show up after the whole count finishes. - -And if we use `setTimeout` to split it into pieces then changes are applied in-between the runs, so this looks better: - -```html run -
- - -``` - -Now the `
` shows increasing values of `i`. - ## Summary - Methods `setInterval(func, delay, ...args)` and `setTimeout(func, delay, ...args)` allow to run the `func` regularly/once after `delay` milliseconds. - To cancel the execution, we should call `clearInterval/clearTimeout` with the value returned by `setInterval/setTimeout`. -- Nested `setTimeout` calls is a more flexible alternative to `setInterval`. Also they can guarantee the minimal time *between* the executions. -- Zero-timeout scheduling `setTimeout(func, 0)` (the same as `setTimeout(func)`) is used to schedule the call "as soon as possible, but after the current code is complete". - -Some use cases of `setTimeout(func)`: -- To split CPU-hungry tasks into pieces, so that the script doesn't "hang" -- To let the browser do something else while the process is going on (paint the progress bar). +- Nested `setTimeout` calls is a more flexible alternative to `setInterval`, allowing to set the time *between* executions more precisely. +- Zero delay scheduling with `setTimeout(func, 0)` (the same as `setTimeout(func)`) is used to schedule the call "as soon as possible, but after the current code is complete". +- The browser limits the minimal delay for five or more nested call of `setTimeout` or for `setInterval` (after 5th call) to 4ms. That's for historical reasons. -Please note that all scheduling methods do not *guarantee* the exact delay. We should not rely on that in the scheduled code. +Please note that all scheduling methods do not *guarantee* the exact delay. For example, the in-browser timer may slow down for a lot of reasons: - The CPU is overloaded. - The browser tab is in the background mode. - The laptop is on battery. -All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and settings. +All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings. diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.png b/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.png deleted file mode 100644 index 844c53788..000000000 Binary files a/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.png and /dev/null differ diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.svg b/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.svg new file mode 100644 index 000000000..9a214c548 --- /dev/null +++ b/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval.svg @@ -0,0 +1 @@ +func(1)func(2)func(3)100200300 \ No newline at end of file diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval@2x.png b/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval@2x.png deleted file mode 100644 index 4fbf122c5..000000000 Binary files a/1-js/06-advanced-functions/08-settimeout-setinterval/setinterval-interval@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.png b/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.png deleted file mode 100644 index f59e157fb..000000000 Binary files a/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.png and /dev/null differ diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.svg b/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.svg new file mode 100644 index 000000000..13b22a892 --- /dev/null +++ b/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval.svg @@ -0,0 +1 @@ +func(1)func(2)func(3)100100 \ No newline at end of file diff --git a/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval@2x.png b/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval@2x.png deleted file mode 100644 index ed99391cf..000000000 Binary files a/1-js/06-advanced-functions/08-settimeout-setinterval/settimeout-interval@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/04-throttle/task.md b/1-js/06-advanced-functions/09-call-apply-decorators/04-throttle/task.md index 8dd77368d..567c9ce7a 100644 --- a/1-js/06-advanced-functions/09-call-apply-decorators/04-throttle/task.md +++ b/1-js/06-advanced-functions/09-call-apply-decorators/04-throttle/task.md @@ -14,18 +14,18 @@ Let's check the real-life application to better understand that requirement and In browser we can setup a function to run at every mouse movement and get the pointer location as it moves. During an active mouse usage, this function usually runs very frequently, can be something like 100 times per second (every 10 ms). -**The tracking function should update some information on the web-page.** +**We'd like to update some information on the web-page when the pointer moves.** -Updating function `update()` is too heavy to do it on every micro-movement. There is also no sense in making it more often than once per 100ms. +...But updating function `update()` is too heavy to do it on every micro-movement. There is also no sense in updating more often than once per 100ms. -So we'll wrap it into the decorator: use `throttle(update, 100)` as the function to run on each mouse move instead of the original `update()`. The decorator will be called often, but `update()` will be called at maximum once per 100ms. +So we'll wrap it into the decorator: use `throttle(update, 100)` as the function to run on each mouse move instead of the original `update()`. The decorator will be called often, but forward the call to `update()` at maximum once per 100ms. Visually, it will look like this: -1. For the first mouse movement the decorated variant passes the call to `update`. That's important, the user sees our reaction to their move immediately. +1. For the first mouse movement the decorated variant immediately passes the call to `update`. That's important, the user sees our reaction to their move immediately. 2. Then as the mouse moves on, until `100ms` nothing happens. The decorated variant ignores calls. -3. At the end of `100ms` -- one more `update` happens with the last coordinates. -4. Then, finally, the mouse stops somewhere. The decorated variant waits until `100ms` expire and then runs `update` with last coordinates. So, perhaps the most important, the final mouse coordinates are processed. +3. At the end of `100ms` -- one more `update` happens with the last coordinates. +4. Then, finally, the mouse stops somewhere. The decorated variant waits until `100ms` expire and then runs `update` with last coordinates. So, quite important, the final mouse coordinates are processed. A code example: diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/article.md b/1-js/06-advanced-functions/09-call-apply-decorators/article.md index 33a4bb8f3..3ca987c47 100644 --- a/1-js/06-advanced-functions/09-call-apply-decorators/article.md +++ b/1-js/06-advanced-functions/09-call-apply-decorators/article.md @@ -6,9 +6,9 @@ JavaScript gives exceptional flexibility when dealing with functions. They can b Let's say we have a function `slow(x)` which is CPU-heavy, but its results are stable. In other words, for the same `x` it always returns the same result. -If the function is called often, we may want to cache (remember) the results for different `x` to avoid spending extra-time on recalculations. +If the function is called often, we may want to cache (remember) the results to avoid spending extra-time on recalculations. -But instead of adding that functionality into `slow()` we'll create a wrapper. As we'll see, there are many benefits of doing so. +But instead of adding that functionality into `slow()` we'll create a wrapper function, that adds caching. As we'll see, there are many benefits of doing so. Here's the code, and explanations follow: @@ -23,13 +23,13 @@ function cachingDecorator(func) { let cache = new Map(); return function(x) { - if (cache.has(x)) { // if the result is in the map - return cache.get(x); // return it + if (cache.has(x)) { // if there's such key in cache + return cache.get(x); // read the result from it } - let result = func(x); // otherwise call func + let result = func(x); // otherwise call func - cache.set(x, result); // and cache (remember) the result + cache.set(x, result); // and cache (remember) the result return result; }; } @@ -49,18 +49,16 @@ The idea is that we can call `cachingDecorator` for any function, and it will re By separating caching from the main function code we also keep the main code simpler. -Now let's get into details of how it works. - The result of `cachingDecorator(func)` is a "wrapper": `function(x)` that "wraps" the call of `func(x)` into caching logic: -![](decorator-makecaching-wrapper.png) +![](decorator-makecaching-wrapper.svg) -As we can see, the wrapper returns the result of `func(x)` "as is". From an outside code, the wrapped `slow` function still does the same. It just got a caching aspect added to its behavior. +From an outside code, the wrapped `slow` function still does the same. It just got a caching aspect added to its behavior. To summarize, there are several benefits of using a separate `cachingDecorator` instead of altering the code of `slow` itself: - The `cachingDecorator` is reusable. We can apply it to another function. -- The caching logic is separate, it did not increase the complexity of `slow` itself (if there were any). +- The caching logic is separate, it did not increase the complexity of `slow` itself (if there was any). - We can combine multiple decorators if needed (other decorators will follow). @@ -231,9 +229,7 @@ let worker = { worker.slow = cachingDecorator(worker.slow); ``` -We have two tasks to solve here. - -First is how to use both arguments `min` and `max` for the key in `cache` map. Previously, for a single argument `x` we could just `cache.set(x, result)` to save the result and `cache.get(x)` to retrieve it. But now we need to remember the result for a *combination of arguments* `(min,max)`. The native `Map` takes single value only as the key. +Previously, for a single argument `x` we could just `cache.set(x, result)` to save the result and `cache.get(x)` to retrieve it. But now we need to remember the result for a *combination of arguments* `(min,max)`. The native `Map` takes single value only as the key. There are many solutions possible: @@ -241,85 +237,11 @@ There are many solutions possible: 2. Use nested maps: `cache.set(min)` will be a `Map` that stores the pair `(max, result)`. So we can get `result` as `cache.get(min).get(max)`. 3. Join two values into one. In our particular case we can just use a string `"min,max"` as the `Map` key. For flexibility, we can allow to provide a *hashing function* for the decorator, that knows how to make one value from many. - For many practical applications, the 3rd variant is good enough, so we'll stick to it. -The second task to solve is how to pass many arguments to `func`. Currently, the wrapper `function(x)` assumes a single argument, and `func.call(this, x)` passes it. - -Here we can use another built-in method [func.apply](mdn:js/Function/apply). - -The syntax is: - -```js -func.apply(context, args) -``` - -It runs the `func` setting `this=context` and using an array-like object `args` as the list of arguments. - - -For instance, these two calls are almost the same: - -```js -func(1, 2, 3); -func.apply(context, [1, 2, 3]) -``` - -Both run `func` giving it arguments `1,2,3`. But `apply` also sets `this=context`. - -For instance, here `say` is called with `this=user` and `messageData` as a list of arguments: - -```js run -function say(time, phrase) { - alert(`[${time}] ${this.name}: ${phrase}`); -} - -let user = { name: "John" }; - -let messageData = ['10:00', 'Hello']; // become time and phrase - -*!* -// user becomes this, messageData is passed as a list of arguments (time, phrase) -say.apply(user, messageData); // [10:00] John: Hello (this=user) -*/!* -``` - -The only syntax difference between `call` and `apply` is that `call` expects a list of arguments, while `apply` takes an array-like object with them. - -We already know the spread operator `...` from the chapter that can pass an array (or any iterable) as a list of arguments. So if we use it with `call`, we can achieve almost the same as `apply`. - -These two calls are almost equivalent: - -```js -let args = [1, 2, 3]; - -*!* -func.call(context, ...args); // pass an array as list with spread operator -func.apply(context, args); // is same as using apply -*/!* -``` - -If we look more closely, there's a minor difference between such uses of `call` and `apply`. - -- The spread operator `...` allows to pass *iterable* `args` as the list to `call`. -- The `apply` accepts only *array-like* `args`. - -So, these calls complement each other. Where we expect an iterable, `call` works, where we expect an array-like, `apply` works. - -And if `args` is both iterable and array-like, like a real array, then we technically could use any of them, but `apply` will probably be faster, because it's a single operation. Most JavaScript engines internally optimize it better than a pair `call + spread`. - -One of the most important uses of `apply` is passing the call to another function, like this: - -```js -let wrapper = function() { - return anotherFunction.apply(this, arguments); -}; -``` - -That's called *call forwarding*. The `wrapper` passes everything it gets: the context `this` and arguments to `anotherFunction` and returns back its result. - -When an external code calls such `wrapper`, it is indistinguishable from the call of the original function. +Also we need to replace `func.call(this, x)` with `func.call(this, ...arguments)`, to pass all arguments to the wrapped function call, not just the first one. -Now let's bake it all into the more powerful `cachingDecorator`: +Here's a more powerful `cachingDecorator`: ```js run let worker = { @@ -340,7 +262,7 @@ function cachingDecorator(func, hash) { } *!* - let result = func.apply(this, arguments); // (**) + let result = func.call(this, ...arguments); // (**) */!* cache.set(key, result); @@ -358,13 +280,52 @@ alert( worker.slow(3, 5) ); // works alert( "Again " + worker.slow(3, 5) ); // same (cached) ``` -Now the wrapper operates with any number of arguments. +Now it works with any number of arguments. There are two changes: - In the line `(*)` it calls `hash` to create a single key from `arguments`. Here we use a simple "joining" function that turns arguments `(3, 5)` into the key `"3,5"`. More complex cases may require other hashing functions. -- Then `(**)` uses `func.apply` to pass both the context and all arguments the wrapper got (no matter how many) to the original function. +- Then `(**)` uses `func.call(this, ...arguments)` to pass both the context and all arguments the wrapper got (not just the first one) to the original function. +Instead of `func.call(this, ...arguments)` we could use `func.apply(this, arguments)`. + +The syntax of built-in method [func.apply](mdn:js/Function/apply) is: + +```js +func.apply(context, args) +``` + +It runs the `func` setting `this=context` and using an array-like object `args` as the list of arguments. + +The only syntax difference between `call` and `apply` is that `call` expects a list of arguments, while `apply` takes an array-like object with them. + +So these two calls are almost equivalent: + +```js +func.call(context, ...args); // pass an array as list with spread operator +func.apply(context, args); // is same as using apply +``` + +There's only a minor difference: + +- The spread operator `...` allows to pass *iterable* `args` as the list to `call`. +- The `apply` accepts only *array-like* `args`. + +So, these calls complement each other. Where we expect an iterable, `call` works, where we expect an array-like, `apply` works. + +And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but `apply` will probably be faster, because most JavaScript engines internally optimize it better. + +Passing all arguments along with the context to another function is called *call forwarding*. + +That's the simplest form of it: + +```js +let wrapper = function() { + return func.apply(this, arguments); +}; +``` + +When an external code calls such `wrapper`, it is indistinguishable from the call of the original function `func`. ## Borrowing a method [#method-borrowing] @@ -450,10 +411,9 @@ The generic *call forwarding* is usually done with `apply`: ```js let wrapper = function() { return original.apply(this, arguments); -} +}; ``` We also saw an example of *method borrowing* when we take a method from an object and `call` it in the context of another object. It is quite common to take array methods and apply them to `arguments`. The alternative is to use rest parameters object that is a real array. - There are many decorators there in the wild. Check how well you got them by solving the tasks of this chapter. diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.png b/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.png deleted file mode 100644 index d9541c768..000000000 Binary files a/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.png and /dev/null differ diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.svg b/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.svg new file mode 100644 index 000000000..5fc7743f0 --- /dev/null +++ b/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper.svg @@ -0,0 +1 @@ +wrapperaround the function \ No newline at end of file diff --git a/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper@2x.png b/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper@2x.png deleted file mode 100644 index 17eef3f18..000000000 Binary files a/1-js/06-advanced-functions/09-call-apply-decorators/decorator-makecaching-wrapper@2x.png and /dev/null differ diff --git a/1-js/06-advanced-functions/11-currying-partials/1-ask-currying/solution.md b/1-js/06-advanced-functions/10-bind/6-ask-partial/solution.md similarity index 100% rename from 1-js/06-advanced-functions/11-currying-partials/1-ask-currying/solution.md rename to 1-js/06-advanced-functions/10-bind/6-ask-partial/solution.md diff --git a/1-js/06-advanced-functions/11-currying-partials/1-ask-currying/task.md b/1-js/06-advanced-functions/10-bind/6-ask-partial/task.md similarity index 100% rename from 1-js/06-advanced-functions/11-currying-partials/1-ask-currying/task.md rename to 1-js/06-advanced-functions/10-bind/6-ask-partial/task.md diff --git a/1-js/06-advanced-functions/10-bind/article.md b/1-js/06-advanced-functions/10-bind/article.md index 06e2000ff..ce0c94a50 100644 --- a/1-js/06-advanced-functions/10-bind/article.md +++ b/1-js/06-advanced-functions/10-bind/article.md @@ -5,13 +5,13 @@ libs: # Function binding -When using `setTimeout` with object methods or passing object methods along, there's a known problem: "losing `this`". +When passing object methods as callbacks, for instance to `setTimeout`, there's a known problem: "losing `this`". -Suddenly, `this` just stops working right. The situation is typical for novice developers, but happens with experienced ones as well. +In this chapter we'll see the ways to fix it. ## Losing "this" -We already know that in JavaScript it's easy to lose `this`. Once a method is passed somewhere separately from the object -- `this` is lost. +We've already seen examples of losing `this`. Once a method is passed somewhere separately from the object -- `this` is lost. Here's how it may happen with `setTimeout`: @@ -37,7 +37,7 @@ let f = user.sayHi; setTimeout(f, 1000); // lost user context ``` -The method `setTimeout` in-browser is a little special: it sets `this=window` for the function call (for Node.js, `this` becomes the timer object, but doesn't really matter here). So for `this.firstName` it tries to get `window.firstName`, which does not exist. In other similar cases as we'll see, usually `this` just becomes `undefined`. +The method `setTimeout` in-browser is a little special: it sets `this=window` for the function call (for Node.js, `this` becomes the timer object, but doesn't really matter here). So for `this.firstName` it tries to get `window.firstName`, which does not exist. In other similar cases, usually `this` just becomes `undefined`. The task is quite typical -- we want to pass an object method somewhere else (here -- to the scheduler) where it will be called. How to make sure that it will be called in the right context? @@ -196,8 +196,124 @@ for (let key in user) { JavaScript libraries also provide functions for convenient mass binding , e.g. [_.bindAll(obj)](http://lodash.com/docs#bindAll) in lodash. ```` +## Partial functions + +Until now we have only been talking about binding `this`. Let's take it a step further. + +We can bind not only `this`, but also arguments. That's rarely done, but sometimes can be handy. + +The full syntax of `bind`: + +```js +let bound = func.bind(context, [arg1], [arg2], ...); +``` + +It allows to bind context as `this` and starting arguments of the function. + +For instance, we have a multiplication function `mul(a, b)`: + +```js +function mul(a, b) { + return a * b; +} +``` + +Let's use `bind` to create a function `double` on its base: + +```js run +function mul(a, b) { + return a * b; +} + +*!* +let double = mul.bind(null, 2); +*/!* + +alert( double(3) ); // = mul(2, 3) = 6 +alert( double(4) ); // = mul(2, 4) = 8 +alert( double(5) ); // = mul(2, 5) = 10 +``` + +The call to `mul.bind(null, 2)` creates a new function `double` that passes calls to `mul`, fixing `null` as the context and `2` as the first argument. Further arguments are passed "as is". + +That's called [partial function application](https://en.wikipedia.org/wiki/Partial_application) -- we create a new function by fixing some parameters of the existing one. + +Please note that here we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`. + +The function `triple` in the code below triples the value: + +```js run +function mul(a, b) { + return a * b; +} + +*!* +let triple = mul.bind(null, 3); +*/!* + +alert( triple(3) ); // = mul(3, 3) = 9 +alert( triple(4) ); // = mul(3, 4) = 12 +alert( triple(5) ); // = mul(3, 5) = 15 +``` + +Why do we usually make a partial function? + +The benefit is that we can create an independent function with a readable name (`double`, `triple`). We can use it and not provide first argument of every time as it's fixed with `bind`. + +In other cases, partial application is useful when we have a very generic function and want a less universal variant of it for convenience. + +For instance, we have a function `send(from, to, text)`. Then, inside a `user` object we may want to use a partial variant of it: `sendTo(to, text)` that sends from the current user. + +## Going partial without context + +What if we'd like to fix some arguments, but not the context `this`? For example, for an object method. + +The native `bind` does not allow that. We can't just omit the context and jump to arguments. + +Fortunately, a helper function `partial` for binding only arguments can be easily implemented. + +Like this: + +```js run +*!* +function partial(func, ...argsBound) { + return function(...args) { // (*) + return func.call(this, ...argsBound, ...args); + } +} +*/!* + +// Usage: +let user = { + firstName: "John", + say(time, phrase) { + alert(`[${time}] ${this.firstName}: ${phrase}!`); + } +}; + +// add a partial method with fixed time +user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes()); + +user.sayNow("Hello"); +// Something like: +// [10:00] John: Hello! +``` + +The result of `partial(func[, arg1, arg2...])` call is a wrapper `(*)` that calls `func` with: +- Same `this` as it gets (for `user.sayNow` call it's `user`) +- Then gives it `...argsBound` -- arguments from the `partial` call (`"10:00"`) +- Then gives it `...args` -- arguments given to the wrapper (`"Hello"`) + +So easy to do it with the spread operator, right? + +Also there's a ready [_.partial](https://lodash.com/docs#partial) implementation from lodash library. + ## Summary Method `func.bind(context, ...args)` returns a "bound variant" of function `func` that fixes the context `this` and first arguments if given. -Usually we apply `bind` to fix `this` in an object method, so that we can pass it somewhere. For example, to `setTimeout`. There are more reasons to `bind` in the modern development, we'll meet them later. +Usually we apply `bind` to fix `this` for an object method, so that we can pass it somewhere. For example, to `setTimeout`. + +When we fix some arguments of an existing function, the resulting (less universal) function is called *partially applied* or *partial*. + +Partials are convenient when we don't want to repeat the same argument over and over again. Like if we have a `send(from, to)` function, and `from` should always be the same for our task, we can get a partial and go on with it. diff --git a/1-js/06-advanced-functions/11-currying-partials/article.md b/1-js/06-advanced-functions/11-currying-partials/article.md deleted file mode 100644 index e8a3d7bdf..000000000 --- a/1-js/06-advanced-functions/11-currying-partials/article.md +++ /dev/null @@ -1,304 +0,0 @@ -libs: - - lodash - ---- - -# Currying and partials - -Until now we have only been talking about binding `this`. Let's take it a step further. - -We can bind not only `this`, but also arguments. That's rarely done, but sometimes can be handy. - -The full syntax of `bind`: - -```js -let bound = func.bind(context, arg1, arg2, ...); -``` - -It allows to bind context as `this` and starting arguments of the function. - -For instance, we have a multiplication function `mul(a, b)`: - -```js -function mul(a, b) { - return a * b; -} -``` - -Let's use `bind` to create a function `double` on its base: - -```js run -function mul(a, b) { - return a * b; -} - -*!* -let double = mul.bind(null, 2); -*/!* - -alert( double(3) ); // = mul(2, 3) = 6 -alert( double(4) ); // = mul(2, 4) = 8 -alert( double(5) ); // = mul(2, 5) = 10 -``` - -The call to `mul.bind(null, 2)` creates a new function `double` that passes calls to `mul`, fixing `null` as the context and `2` as the first argument. Further arguments are passed "as is". - -That's called [partial function application](https://en.wikipedia.org/wiki/Partial_application) -- we create a new function by fixing some parameters of the existing one. - -Please note that here we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`. - -The function `triple` in the code below triples the value: - -```js run -function mul(a, b) { - return a * b; -} - -*!* -let triple = mul.bind(null, 3); -*/!* - -alert( triple(3) ); // = mul(3, 3) = 9 -alert( triple(4) ); // = mul(3, 4) = 12 -alert( triple(5) ); // = mul(3, 5) = 15 -``` - -Why do we usually make a partial function? - -The benefit is that we can create an independent function with a readable name (`double`, `triple`). We can use it and not provide first argument of every time as it's fixed with `bind`. - -In other cases, partial application is useful when we have a very generic function and want a less universal variant of it for convenience. - -For instance, we have a function `send(from, to, text)`. Then, inside a `user` object we may want to use a partial variant of it: `sendTo(to, text)` that sends from the current user. - -## Going partial without context - -What if we'd like to fix some arguments, but not bind `this`? - -The native `bind` does not allow that. We can't just omit the context and jump to arguments. - -Fortunately, a `partial` function for binding only arguments can be easily implemented. - -Like this: - -```js run -*!* -function partial(func, ...argsBound) { - return function(...args) { // (*) - return func.call(this, ...argsBound, ...args); - } -} -*/!* - -// Usage: -let user = { - firstName: "John", - say(time, phrase) { - alert(`[${time}] ${this.firstName}: ${phrase}!`); - } -}; - -// add a partial method that says something now by fixing the first argument -user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes()); - -user.sayNow("Hello"); -// Something like: -// [10:00] John: Hello! -``` - -The result of `partial(func[, arg1, arg2...])` call is a wrapper `(*)` that calls `func` with: -- Same `this` as it gets (for `user.sayNow` call it's `user`) -- Then gives it `...argsBound` -- arguments from the `partial` call (`"10:00"`) -- Then gives it `...args` -- arguments given to the wrapper (`"Hello"`) - -So easy to do it with the spread operator, right? - -Also there's a ready [_.partial](https://lodash.com/docs#partial) implementation from lodash library. - -## Currying - -Sometimes people mix up partial function application mentioned above with another thing named "currying". That's another interesting technique of working with functions that we just have to mention here. - -[Currying](https://en.wikipedia.org/wiki/Currying) is a transformation of functions that translates a function from callable as `f(a, b, c)` into callable as `f(a)(b)(c)`. In JavaScript, we usually make a wrapper to keep the original function. - -Currying doesn't call a function. It just transforms it. - -Let's create a helper `curry(f)` function that performs currying for a two-argument `f`. In other words, `curry(f)` for two-argument `f(a, b)` translates it into `f(a)(b)` - -```js run -*!* -function curry(f) { // curry(f) does the currying transform - return function(a) { - return function(b) { - return f(a, b); - }; - }; -} -*/!* - -// usage -function sum(a, b) { - return a + b; -} - -let carriedSum = curry(sum); - -alert( carriedSum(1)(2) ); // 3 -``` - -As you can see, the implementation is a series of wrappers. - -- The result of `curry(func)` is a wrapper `function(a)`. -- When it is called like `sum(1)`, the argument is saved in the Lexical Environment, and a new wrapper is returned `function(b)`. -- Then `sum(1)(2)` finally calls `function(b)` providing `2`, and it passes the call to the original multi-argument `sum`. - -More advanced implementations of currying like [_.curry](https://lodash.com/docs#curry) from lodash library do something more sophisticated. They return a wrapper that allows a function to be called normally when all arguments are supplied *or* returns a partial otherwise. - -```js -function curry(f) { - return function(...args) { - // if args.length == f.length (as many arguments as f has), - // then pass the call to f - // otherwise return a partial function that fixes args as first arguments - }; -} -``` - -## Currying? What for? - -To understand the benefits we definitely need a worthy real-life example. - -Advanced currying allows the function to be both callable normally and partially. - -For instance, we have the logging function `log(date, importance, message)` that formats and outputs the information. In real projects such functions also have many other useful features like sending logs over the network, here we just use `alert`: - -```js -function log(date, importance, message) { - alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`); -} -``` - -Let's curry it! - -```js -log = _.curry(log); -``` - -After that `log` work both the normal way and in the curried form: - -```js -log(new Date(), "DEBUG", "some debug"); // log(a,b,c) -log(new Date())("DEBUG")("some debug"); // log(a)(b)(c) -``` - -Now we can easily make a convenience function for current logs: - -```js -// currentLog will be the partial of log with fixed first argument -let logNow = log(new Date()); - -// use it -logNow("INFO", "message"); // [HH:mm] INFO message -``` - -And here's a convenience function for current debug messages: - -```js -let debugNow = logNow("DEBUG"); - -debugNow("message"); // [HH:mm] DEBUG message -``` - -So: -1. We didn't lose anything after currying: `log` is still callable normally. -2. We were able to generate partial functions such as for today's logs. - -## Advanced curry implementation - -In case you'd like to get in details (not obligatory!), here's the "advanced" curry implementation that we could use above. - -It's pretty short: - -```js -function curry(func) { - - return function curried(...args) { - if (args.length >= func.length) { - return func.apply(this, args); - } else { - return function(...args2) { - return curried.apply(this, args.concat(args2)); - } - } - }; - -} -``` - -Usage examples: - -```js -function sum(a, b, c) { - return a + b + c; -} - -let curriedSum = curry(sum); - -alert( curriedSum(1, 2, 3) ); // 6, still callable normally -alert( curriedSum(1)(2,3) ); // 6, currying of 1st arg -alert( curriedSum(1)(2)(3) ); // 6, full currying -``` - -The new `curry` may look complicated, but it's actually easy to understand. - -The result of `curry(func)` is the wrapper `curried` that looks like this: - -```js -// func is the function to transform -function curried(...args) { - if (args.length >= func.length) { // (1) - return func.apply(this, args); - } else { - return function pass(...args2) { // (2) - return curried.apply(this, args.concat(args2)); - } - } -}; -``` - -When we run it, there are two branches: - -1. Call now: if passed `args` count is the same as the original function has in its definition (`func.length`) or longer, then just pass the call to it. -2. Get a partial: otherwise, `func` is not called yet. Instead, another wrapper `pass` is returned, that will re-apply `curried` providing previous arguments together with the new ones. Then on a new call, again, we'll get either a new partial (if not enough arguments) or, finally, the result. - -For instance, let's see what happens in the case of `sum(a, b, c)`. Three arguments, so `sum.length = 3`. - -For the call `curried(1)(2)(3)`: - -1. The first call `curried(1)` remembers `1` in its Lexical Environment, and returns a wrapper `pass`. -2. The wrapper `pass` is called with `(2)`: it takes previous args (`1`), concatenates them with what it got `(2)` and calls `curried(1, 2)` with them together. - - As the argument count is still less than 3, `curry` returns `pass`. -3. The wrapper `pass` is called again with `(3)`, for the next call `pass(3)` takes previous args (`1`, `2`) and adds `3` to them, making the call `curried(1, 2, 3)` -- there are `3` arguments at last, they are given to the original function. - -If that's still not obvious, just trace the calls sequence in your mind or on the paper. - -```smart header="Fixed-length functions only" -The currying requires the function to have a known fixed number of arguments. -``` - -```smart header="A little more than currying" -By definition, currying should convert `sum(a, b, c)` into `sum(a)(b)(c)`. - -But most implementations of currying in JavaScript are advanced, as described: they also keep the function callable in the multi-argument variant. -``` - -## Summary - -- When we fix some arguments of an existing function, the resulting (less universal) function is called *a partial*. We can use `bind` to get a partial, but there are other ways also. - - Partials are convenient when we don't want to repeat the same argument over and over again. Like if we have a `send(from, to)` function, and `from` should always be the same for our task, we can get a partial and go on with it. - -- *Currying* is a transform that makes `f(a,b,c)` callable as `f(a)(b)(c)`. JavaScript implementations usually both keep the function callable normally and return the partial if arguments count is not enough. - - Currying is great when we want easy partials. As we've seen in the logging example: the universal function `log(date, importance, message)` after currying gives us partials when called with one argument like `log(date)` or two arguments `log(date, importance)`. diff --git a/1-js/06-advanced-functions/12-arrow-functions/article.md b/1-js/06-advanced-functions/12-arrow-functions/article.md index 1ade1a419..abc5dd80a 100644 --- a/1-js/06-advanced-functions/12-arrow-functions/article.md +++ b/1-js/06-advanced-functions/12-arrow-functions/article.md @@ -2,7 +2,7 @@ Let's revisit arrow functions. -Arrow functions are not just a "shorthand" for writing small stuff. +Arrow functions are not just a "shorthand" for writing small stuff. They have some very specific and useful features. JavaScript is full of situations where we need to write a small function, that's executed somewhere else. @@ -14,7 +14,7 @@ For instance: It's in the very spirit of JavaScript to create a function and pass it somewhere. -And in such functions we usually don't want to leave the current context. +And in such functions we usually don't want to leave the current context. That's where arrow functions come in handy. ## Arrow functions have no "this" diff --git a/1-js/07-object-properties/01-property-descriptors/article.md b/1-js/07-object-properties/01-property-descriptors/article.md index 7768b3557..8ac5fd0d4 100644 --- a/1-js/07-object-properties/01-property-descriptors/article.md +++ b/1-js/07-object-properties/01-property-descriptors/article.md @@ -63,7 +63,7 @@ Object.defineProperty(obj, propertyName, descriptor) ``` `obj`, `propertyName` -: The object and property to work on. +: The object and its property to apply the descriptor. `descriptor` : Property descriptor to apply. @@ -116,31 +116,34 @@ Object.defineProperty(user, "name", { }); *!* -user.name = "Pete"; // Error: Cannot assign to read only property 'name'... +user.name = "Pete"; // Error: Cannot assign to read only property 'name' */!* ``` Now no one can change the name of our user, unless they apply their own `defineProperty` to override ours. -Here's the same operation, but for the case when a property doesn't exist: +```smart header="Errors appear only in strict mode" +In the non-strict mode, no errors occur when writing to read-only properties and such. But the operation still won't succeed. Flag-violating actions are just silently ignored in non-strict. +``` + +Here's the same example, but the property is created from scratch: ```js run let user = { }; Object.defineProperty(user, "name", { *!* - value: "Pete", + value: "John", // for new properties need to explicitly list what's true enumerable: true, configurable: true */!* }); -alert(user.name); // Pete -user.name = "Alice"; // Error +alert(user.name); // John +user.name = "Pete"; // Error ``` - ## Non-enumerable Now let's add a custom `toString` to `user`. @@ -239,10 +242,6 @@ Object.defineProperty(user, "name", {writable: true}); // Error */!* ``` -```smart header="Errors appear only in use strict" -In the non-strict mode, no errors occur when writing to read-only properties and such. But the operation still won't succeed. Flag-violating actions are just silently ignored in non-strict. -``` - ## Object.defineProperties There's a method [Object.defineProperties(obj, descriptors)](mdn:js/Object/defineProperties) that allows to define many properties at once. diff --git a/1-js/07-object-properties/02-property-accessors/article.md b/1-js/07-object-properties/02-property-accessors/article.md index f316cc23f..78fab9a63 100644 --- a/1-js/07-object-properties/02-property-accessors/article.md +++ b/1-js/07-object-properties/02-property-accessors/article.md @@ -34,7 +34,7 @@ let user = { }; ``` -Now we want to add a "fullName" property, that should be "John Smith". Of course, we don't want to copy-paste existing information, so we can implement it as an accessor: +Now we want to add a `fullName` property, that should be `"John Smith"`. Of course, we don't want to copy-paste existing information, so we can implement it as an accessor: ```js run let user = { @@ -55,7 +55,19 @@ alert(user.fullName); // John Smith From outside, an accessor property looks like a regular one. That's the idea of accessor properties. We don't *call* `user.fullName` as a function, we *read* it normally: the getter runs behind the scenes. -As of now, `fullName` has only a getter. If we attempt to assign `user.fullName=`, there will be an error. +As of now, `fullName` has only a getter. If we attempt to assign `user.fullName=`, there will be an error: + +```js run +let user = { + get fullName() { + return `...`; + } +}; + +*!* +user.fullName = "Test"; // Error (property has only a getter) +*/!* +``` Let's fix it by adding a setter for `user.fullName`: @@ -84,13 +96,8 @@ alert(user.surname); // Cooper As the result, we have a "virtual" property `fullName`. It is readable and writable, but in fact does not exist. -```smart header="Accessor properties are only accessible with get/set" -Once a property is defined with `get prop()` or `set prop()`, it's an accessor property, not a data property any more. - -- If there's a getter -- we can read `object.prop`, otherwise we can't. -- If there's a setter -- we can set `object.prop=...`, otherwise we can't. - -And in either case we can't `delete` an accessor property. +```smart header="No support for `delete`" +An attempt to `delete` on accessor property causes an error. ``` @@ -100,7 +107,7 @@ Descriptors for accessor properties are different -- as compared with data prope For accessor properties, there is no `value` and `writable`, but instead there are `get` and `set` functions. -So an accessor descriptor may have: +That is, an accessor descriptor may have: - **`get`** -- a function without arguments, that works when a property is read, - **`set`** -- a function with one argument, that is called when the property is set, @@ -132,7 +139,7 @@ alert(user.fullName); // John Smith for(let key in user) alert(key); // name, surname ``` -Please note once again that a property can be either an accessor or a data property, not both. +Please note once again that a property can be either an accessor (has `get/set` methods) or a data property (has a `value`), not both. If we try to supply both `get` and `value` in the same descriptor, there will be an error: @@ -151,9 +158,9 @@ Object.defineProperty({}, 'prop', { ## Smarter getters/setters -Getters/setters can be used as wrappers over "real" property values to gain more control over them. +Getters/setters can be used as wrappers over "real" property values to gain more control over operations with them. -For instance, if we want to forbid too short names for `user`, we can store `name` in a special property `_name`. And filter assignments in the setter: +For instance, if we want to forbid too short names for `user`, we can have a setter `name` and keep the value in a separate property `_name`: ```js run let user = { @@ -176,14 +183,16 @@ alert(user.name); // Pete user.name = ""; // Name is too short... ``` -Technically, the external code may still access the name directly by using `user._name`. But there is a widely known agreement that properties starting with an underscore `"_"` are internal and should not be touched from outside the object. +So, the name is stored in `_name` property, and the access is done via getter and setter. + +Technically, external code is able to access the name directly by using `user._name`. But there is a widely known convention that properties starting with an underscore `"_"` are internal and should not be touched from outside the object. ## Using for compatibility -One of the great ideas behind getters and setters -- they allow to take control over a "regular" data property at any moment by replacing it with getter and setter and tweak its behavior. +One of the great uses of accessors -- they allow to take control over a "regular" data property at any moment by replacing it with getter and setter and tweak its behavior. -Let's say we started implementing user objects using data properties `name` and `age`: +Imagine, we started implementing user objects using data properties `name` and `age`: ```js function User(name, age) { @@ -209,7 +218,9 @@ let john = new User("John", new Date(1992, 6, 1)); Now what to do with the old code that still uses `age` property? -We can try to find all such places and fix them, but that takes time and can be hard to do if that code is written/used by many other people. And besides, `age` is a nice thing to have in `user`, right? In some places it's just what we want. +We can try to find all such places and fix them, but that takes time and can be hard to do if that code is used by many other people. And besides, `age` is a nice thing to have in `user`, right? + +Let's keep it. Adding a getter for `age` solves the problem: diff --git a/1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md b/1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md index 002b24b8a..421b57e0a 100644 --- a/1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md +++ b/1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md @@ -6,7 +6,7 @@ importance: 5 The task has two parts. -We have an object: +We have objects: ```js let head = { diff --git a/1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/solution.md b/1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/solution.md index c7d147b9c..4d6ea2653 100644 --- a/1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/solution.md +++ b/1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/solution.md @@ -3,4 +3,5 @@ That's because `this` is an object before the dot, so `rabbit.eat()` modifies `rabbit`. Property lookup and execution are two different things. -The method `rabbit.eat` is first found in the prototype, then executed with `this=rabbit` + +The method `rabbit.eat` is first found in the prototype, then executed with `this=rabbit`. diff --git a/1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md b/1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md index fad4b8860..bd412f126 100644 --- a/1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md +++ b/1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md @@ -10,7 +10,7 @@ Let's look carefully at what's going on in the call `speedy.eat("apple")`. So all hamsters share a single stomach! -Every time the `stomach` is taken from the prototype, then `stomach.push` modifies it "at place". +Both for `lazy.stomach.push(...)` and `speedy.stomach.push()`, the property `stomach` is found in the prototype (as it's not in the object itself), then the new data is pushed into it. Please note that such thing doesn't happen in case of a simple assignment `this.stomach=`: @@ -77,4 +77,4 @@ alert( speedy.stomach ); // apple alert( lazy.stomach ); // ``` -As a common solution, all properties that describe the state of a particular object, like `stomach` above, are usually written into that object. That prevents such problems. +As a common solution, all properties that describe the state of a particular object, like `stomach` above, should be written into that object. That prevents such problems. diff --git a/1-js/08-prototypes/01-prototype-inheritance/article.md b/1-js/08-prototypes/01-prototype-inheritance/article.md index c4dd1aacb..5895a0b37 100644 --- a/1-js/08-prototypes/01-prototype-inheritance/article.md +++ b/1-js/08-prototypes/01-prototype-inheritance/article.md @@ -10,7 +10,7 @@ For instance, we have a `user` object with its properties and methods, and want In JavaScript, objects have a special hidden property `[[Prototype]]` (as named in the specification), that is either `null` or references another object. That object is called "a prototype": -![prototype](object-prototype-empty.png) +![prototype](object-prototype-empty.svg) The prototype is a little bit "magical". When we want to read a property from `object`, and it's missing, JavaScript automatically takes it from the prototype. In programming, such thing is called "prototypal inheritance". Many cool language features and programming techniques are based on it. @@ -66,7 +66,7 @@ Here the line `(*)` sets `animal` to be a prototype of `rabbit`. Then, when `alert` tries to read property `rabbit.eats` `(**)`, it's not in `rabbit`, so JavaScript follows the `[[Prototype]]` reference and finds it in `animal` (look from the bottom up): -![](proto-animal-rabbit.png) +![](proto-animal-rabbit.svg) Here we can say that "`animal` is the prototype of `rabbit`" or "`rabbit` prototypically inherits from `animal`". @@ -97,11 +97,10 @@ rabbit.walk(); // Animal walk The method is automatically taken from the prototype, like this: -![](proto-animal-rabbit-walk.png) +![](proto-animal-rabbit-walk.svg) The prototype chain can be longer: - ```js run let animal = { eats: true, @@ -129,12 +128,12 @@ longEar.walk(); // Animal walk alert(longEar.jumps); // true (from rabbit) ``` -![](proto-animal-rabbit-chain.png) +![](proto-animal-rabbit-chain.svg) -There are actually only two limitations: +There are only two limitations: 1. The references can't go in circles. JavaScript will throw an error if we try to assign `__proto__` in a circle. -2. The value of `__proto__` can be either an object or `null`, other types (like primitives) are ignored. +2. The value of `__proto__` can be either an object or `null`. Other types are ignored. Also it may be obvious, but still: there can be only one `[[Prototype]]`. An object may not inherit from two others. @@ -169,9 +168,9 @@ rabbit.walk(); // Rabbit! Bounce-bounce! From now on, `rabbit.walk()` call finds the method immediately in the object and executes it, without using the prototype: -![](proto-animal-rabbit-walk-2.png) +![](proto-animal-rabbit-walk-2.svg) -That's for data properties only, not for accessors. If a property is a getter/setter, then it behaves like a function: getters/setters are looked up in the prototype. +Accessor properties are an exception, as assignment is handled by a setter function. So writing to such a property is actually the same as calling a function. For that reason `admin.fullName` works correctly in the code below: @@ -245,9 +244,9 @@ alert(animal.isSleeping); // undefined (no such property in the prototype) The resulting picture: -![](proto-animal-rabbit-walk-3.png) +![](proto-animal-rabbit-walk-3.svg) -If we had other objects like `bird`, `snake` etc inheriting from `animal`, they would also gain access to methods of `animal`. But `this` in each method would be the corresponding object, evaluated at the call-time (before dot), not `animal`. So when we write data into `this`, it is stored into these objects. +If we had other objects like `bird`, `snake` etc inheriting from `animal`, they would also gain access to methods of `animal`. But `this` in each method call would be the corresponding object, evaluated at the call-time (before dot), not `animal`. So when we write data into `this`, it is stored into these objects. As a result, methods are shared, but the object state is not. @@ -305,7 +304,7 @@ for(let prop in rabbit) { Here we have the following inheritance chain: `rabbit` inherits from `animal`, that inherits from `Object.prototype` (because `animal` is a literal object `{...}`, so it's by default), and then `null` above it: -![](rabbit-animal-object.png) +![](rabbit-animal-object.svg) Note, there's one funny thing. Where is the method `rabbit.hasOwnProperty` coming from? We did not define it. Looking at the chain we can see that the method is provided by `Object.prototype.hasOwnProperty`. In other words, it's inherited. @@ -313,10 +312,10 @@ Note, there's one funny thing. Where is the method `rabbit.hasOwnProperty` comin The answer is simple: it's not enumerable. Just like all other properties of `Object.prototype`, it has `enumerable:false` flag. That's why they are not listed. -```smart header="All other iteration methods ignore inherited properties" -All other key/value-getting methods, such as `Object.keys`, `Object.values` and so on ignore inherited properties. +```smart header="Almost all other key/value-getting methods ignore inherited properties" +Almost all other key/value-getting methods, such as `Object.keys`, `Object.values` and so on ignore inherited properties. -They only operate on the object itself. Properties from the prototype are taken into account. +They only operate on the object itself. Properties from the prototype are *not* taken into account. ``` ## Summary diff --git a/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.png b/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.png deleted file mode 100644 index 3ecff3fdd..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.svg b/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.svg new file mode 100644 index 000000000..fe4c2cace --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty.svg @@ -0,0 +1 @@ +prototype objectobject[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty@2x.png b/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty@2x.png deleted file mode 100644 index f80e61e68..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/object-prototype-empty@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.png deleted file mode 100644 index 48e02ad18..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.svg new file mode 100644 index 000000000..3e81f262b --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain.svg @@ -0,0 +1 @@ +eats: true walk: functionanimaljumps: truerabbit[[Prototype]]earLength: 10longEar[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain@2x.png deleted file mode 100644 index 1a04db885..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-chain@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.png deleted file mode 100644 index 22b867fc8..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.svg new file mode 100644 index 000000000..3cf5c4c78 --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.svg @@ -0,0 +1 @@ +eats: true walk: functionanimalwalk: functionrabbit[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2@2x.png deleted file mode 100644 index 8d9f9f1ae..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.png deleted file mode 100644 index bc76d64ba..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.svg new file mode 100644 index 000000000..acd420631 --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3.svg @@ -0,0 +1 @@ +walk: function sleep: functionanimalrabbit[[Prototype]]name: "White Rabbit" isSleeping: true \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3@2x.png deleted file mode 100644 index 725a4c150..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-3@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.png deleted file mode 100644 index 29fc6d503..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.svg new file mode 100644 index 000000000..ebdef9587 --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.svg @@ -0,0 +1 @@ +eats: true walk: functionanimaljumps: truerabbit[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk@2x.png deleted file mode 100644 index 724d6111b..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.png deleted file mode 100644 index d50327f0e..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.svg new file mode 100644 index 000000000..735e1f2b3 --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit.svg @@ -0,0 +1 @@ +eats: trueanimaljumps: truerabbit[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit@2x.png deleted file mode 100644 index 0506b92b6..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.png b/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.png deleted file mode 100644 index c37d00780..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.svg b/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.svg new file mode 100644 index 000000000..433bc613f --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin.svg @@ -0,0 +1 @@ +name: "John" surname: "Smith" set fullName: functionisAdmin: true name: "Alice" surname: "Cooper"useradmin[[Prototype]] \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin@2x.png b/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin@2x.png deleted file mode 100644 index 8c3f546eb..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/proto-user-admin@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.png b/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.png deleted file mode 100644 index 3924233dd..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.png and /dev/null differ diff --git a/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.svg b/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.svg new file mode 100644 index 000000000..d32585b43 --- /dev/null +++ b/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object.svg @@ -0,0 +1 @@ +toString: function hasOwnProperty: function ...Object.prototypeanimal[[Prototype]][[Prototype]][[Prototype]]nulleats: truerabbitjumps: true \ No newline at end of file diff --git a/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object@2x.png b/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object@2x.png deleted file mode 100644 index 5350a1935..000000000 Binary files a/1-js/08-prototypes/01-prototype-inheritance/rabbit-animal-object@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/article.md b/1-js/08-prototypes/02-function-prototype/article.md index 2089e96cf..29b3773eb 100644 --- a/1-js/08-prototypes/02-function-prototype/article.md +++ b/1-js/08-prototypes/02-function-prototype/article.md @@ -36,7 +36,7 @@ Setting `Rabbit.prototype = animal` literally states the following: "When a `new That's the resulting picture: -![](proto-constructor-animal-rabbit.png) +![](proto-constructor-animal-rabbit.svg) On the picture, `"prototype"` is a horizontal arrow, meaning a regular property, and `[[Prototype]]` is vertical, meaning the inheritance of `rabbit` from `animal`. @@ -62,7 +62,7 @@ Rabbit.prototype = { constructor: Rabbit }; */ ``` -![](function-prototype-constructor.png) +![](function-prototype-constructor.svg) We can check it: @@ -86,7 +86,7 @@ let rabbit = new Rabbit(); // inherits from {constructor: Rabbit} alert(rabbit.constructor == Rabbit); // true (from prototype) ``` -![](rabbit-prototype-constructor.png) +![](rabbit-prototype-constructor.svg) We can use `constructor` property to create a new object using the same constructor as the existing one. @@ -160,8 +160,8 @@ In this chapter we briefly described the way of setting a `[[Prototype]]` for ob Everything is quite simple, just few notes to make things clear: -- The `F.prototype` property is not the same as `[[Prototype]]`. The only thing `F.prototype` does: it sets `[[Prototype]]` of new objects when `new F()` is called. -- The value of `F.prototype` should be either an object or null: other values won't work. +- The `F.prototype` property (don't mess with `[[Prototype]]`) sets `[[Prototype]]` of new objects when `new F()` is called. +- The value of `F.prototype` should be either an object or `null`: other values won't work. - The `"prototype"` property only has such a special effect when set on a constructor function, and invoked with `new`. On regular objects the `prototype` is nothing special: diff --git a/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.png b/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.png deleted file mode 100644 index 6ab9c6934..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.svg b/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.svg new file mode 100644 index 000000000..35cdc61f1 --- /dev/null +++ b/1-js/08-prototypes/02-function-prototype/function-prototype-constructor.svg @@ -0,0 +1 @@ +Rabbitprototypeconstructordefault "prototype" \ No newline at end of file diff --git a/1-js/08-prototypes/02-function-prototype/function-prototype-constructor@2x.png b/1-js/08-prototypes/02-function-prototype/function-prototype-constructor@2x.png deleted file mode 100644 index 3beb0a573..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/function-prototype-constructor@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring.png b/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring.png deleted file mode 100644 index c47938674..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring@2x.png b/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring@2x.png deleted file mode 100644 index 293c88bf9..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/native-prototypes-array-tostring@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/native-prototypes-classes.png b/1-js/08-prototypes/02-function-prototype/native-prototypes-classes.png deleted file mode 100644 index c4658a929..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/native-prototypes-classes.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/native-prototypes-classes@2x.png b/1-js/08-prototypes/02-function-prototype/native-prototypes-classes@2x.png deleted file mode 100644 index 79445fac9..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/native-prototypes-classes@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/object-prototype-1.png b/1-js/08-prototypes/02-function-prototype/object-prototype-1.png deleted file mode 100644 index a69cad4a1..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/object-prototype-1.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/object-prototype-1@2x.png b/1-js/08-prototypes/02-function-prototype/object-prototype-1@2x.png deleted file mode 100644 index 9d661ac17..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/object-prototype-1@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/object-prototype.png b/1-js/08-prototypes/02-function-prototype/object-prototype.png deleted file mode 100644 index 820ffcc73..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/object-prototype.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/object-prototype@2x.png b/1-js/08-prototypes/02-function-prototype/object-prototype@2x.png deleted file mode 100644 index 1eb7e8749..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/object-prototype@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.png b/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.png deleted file mode 100644 index 4b381460a..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.svg b/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.svg new file mode 100644 index 000000000..3489ecdd8 --- /dev/null +++ b/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit.svg @@ -0,0 +1 @@ +eats: truename: "White Rabbit"animalRabbitrabbit[[Prototype]]prototype \ No newline at end of file diff --git a/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit@2x.png b/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit@2x.png deleted file mode 100644 index c6e6ab5f6..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/proto-constructor-animal-rabbit@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/rabbit-animal-object.png b/1-js/08-prototypes/02-function-prototype/rabbit-animal-object.png deleted file mode 100644 index 3924233dd..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/rabbit-animal-object.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/rabbit-animal-object@2x.png b/1-js/08-prototypes/02-function-prototype/rabbit-animal-object@2x.png deleted file mode 100644 index 5350a1935..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/rabbit-animal-object@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.png b/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.png deleted file mode 100644 index 8f3519a74..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.png and /dev/null differ diff --git a/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.svg b/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.svg new file mode 100644 index 000000000..3e11f275b --- /dev/null +++ b/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor.svg @@ -0,0 +1 @@ +default "prototype"Rabbitrabbit[[Prototype]]prototypeconstructor \ No newline at end of file diff --git a/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor@2x.png b/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor@2x.png deleted file mode 100644 index 07acb8f4a..000000000 Binary files a/1-js/08-prototypes/02-function-prototype/rabbit-prototype-constructor@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/article.md b/1-js/08-prototypes/03-native-prototypes/article.md index d540be5f2..66be00ca1 100644 --- a/1-js/08-prototypes/03-native-prototypes/article.md +++ b/1-js/08-prototypes/03-native-prototypes/article.md @@ -2,7 +2,7 @@ The `"prototype"` property is widely used by the core of JavaScript itself. All built-in constructor functions use it. -We'll see how it is for plain objects first, and then for more complex ones. +First we'll see at the details, and then how to use it for adding new capabilities to built-in objects. ## Object.prototype @@ -19,11 +19,11 @@ Where's the code that generates the string `"[object Object]"`? That's a built-i Here's what's going on: -![](object-prototype.png) +![](object-prototype.svg) When `new Object()` is called (or a literal object `{...}` is created), the `[[Prototype]]` of it is set to `Object.prototype` according to the rule that we discussed in the previous chapter: -![](object-prototype-1.png) +![](object-prototype-1.svg) So then when `obj.toString()` is called the method is taken from `Object.prototype`. @@ -36,7 +36,7 @@ alert(obj.__proto__ === Object.prototype); // true // obj.toString === obj.__proto__.toString == Object.prototype.toString ``` -Please note that there is no additional `[[Prototype]]` in the chain above `Object.prototype`: +Please note that there is no more `[[Prototype]]` in the chain above `Object.prototype`: ```js run alert(Object.prototype.__proto__); // null @@ -46,13 +46,13 @@ alert(Object.prototype.__proto__); // null Other built-in objects such as `Array`, `Date`, `Function` and others also keep methods in prototypes. -For instance, when we create an array `[1, 2, 3]`, the default `new Array()` constructor is used internally. So the array data is written into the new object, and `Array.prototype` becomes its prototype and provides methods. That's very memory-efficient. +For instance, when we create an array `[1, 2, 3]`, the default `new Array()` constructor is used internally. So `Array.prototype` becomes its prototype and provides methods. That's very memory-efficient. -By specification, all of the built-in prototypes have `Object.prototype` on the top. Sometimes people say that "everything inherits from objects". +By specification, all of the built-in prototypes have `Object.prototype` on the top. That's why some people say that "everything inherits from objects". Here's the overall picture (for 3 built-ins to fit): -![](native-prototypes-classes.png) +![](native-prototypes-classes.svg) Let's check the prototypes manually: @@ -79,7 +79,7 @@ alert(arr); // 1,2,3 <-- the result of Array.prototype.toString As we've seen before, `Object.prototype` has `toString` as well, but `Array.prototype` is closer in the chain, so the array variant is used. -![](native-prototypes-array-tostring.png) +![](native-prototypes-array-tostring.svg) In-browser tools like Chrome developer console also show inheritance (`console.dir` may need to be used for built-in objects): @@ -122,7 +122,7 @@ String.prototype.show = function() { During the process of development, we may have ideas for new built-in methods we'd like to have, and we may be tempted to add them to native prototypes. But that is generally a bad idea. ```warn -Prototypes are global, so it's easy to get a conflict. If two libraries add a method `String.prototype.show`, then one of them will be overwriting the other. +Prototypes are global, so it's easy to get a conflict. If two libraries add a method `String.prototype.show`, then one of them will be overwriting the method of the other. So, generally, modifying a native prototype is considered a bad idea. ``` @@ -144,7 +144,7 @@ if (!String.prototype.repeat) { // if there's no such method // actually, the code should be a little bit more complex than that // (the full algorithm is in the specification) - // but even an imperfect polyfill is often considered good enough + // but even an imperfect polyfill is often considered good enough for use return new Array(n + 1).join(this); }; } @@ -161,7 +161,7 @@ That's when we take a method from one object and copy it into another. Some methods of native prototypes are often borrowed. -For instance, if we're making an array-like object, we may want to copy some array methods to it. +For instance, if we're making an array-like object, we may want to copy some `Array` methods to it. E.g. diff --git a/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.png b/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.png deleted file mode 100644 index 6ab9c6934..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.svg b/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.svg new file mode 100644 index 000000000..35cdc61f1 --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor.svg @@ -0,0 +1 @@ +Rabbitprototypeconstructordefault "prototype" \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor@2x.png b/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor@2x.png deleted file mode 100644 index 3beb0a573..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/function-prototype-constructor@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.png b/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.png deleted file mode 100644 index c47938674..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.svg b/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.svg new file mode 100644 index 000000000..770c908c5 --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring.svg @@ -0,0 +1 @@ +toString: function ...Array.prototypetoString: function ...Object.prototype[[Prototype]][[Prototype]][1, 2, 3] \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring@2x.png b/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring@2x.png deleted file mode 100644 index 293c88bf9..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/native-prototypes-array-tostring@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.png b/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.png deleted file mode 100644 index c4658a929..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.svg b/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.svg new file mode 100644 index 000000000..4989df56b --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes.svg @@ -0,0 +1 @@ +toString: function other object methodsObject.prototypenullslice: function other array methods[[Prototype]][[Prototype]][[Prototype]][[Prototype]][[Prototype]][[Prototype]][[Prototype]]Array.prototypecall: function other function methodsFunction.prototypetoFixed: function other number methodsNumber.prototype[1, 2, 3]function f(args) { ... }5 \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes@2x.png b/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes@2x.png deleted file mode 100644 index 79445fac9..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/native-prototypes-classes@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-1.png b/1-js/08-prototypes/03-native-prototypes/object-prototype-1.png deleted file mode 100644 index a69cad4a1..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype-1.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-1.svg b/1-js/08-prototypes/03-native-prototypes/object-prototype-1.svg new file mode 100644 index 000000000..38c33cae1 --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/object-prototype-1.svg @@ -0,0 +1 @@ +constructor: Object toString: function ...Object.prototypeObjectobj = new Object()[[Prototype]]prototype \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-1@2x.png b/1-js/08-prototypes/03-native-prototypes/object-prototype-1@2x.png deleted file mode 100644 index 9d661ac17..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype-1@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-null.png b/1-js/08-prototypes/03-native-prototypes/object-prototype-null.png deleted file mode 100644 index 792c4f423..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype-null.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-null.svg b/1-js/08-prototypes/03-native-prototypes/object-prototype-null.svg new file mode 100644 index 000000000..858f8317e --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/object-prototype-null.svg @@ -0,0 +1 @@ +obj[[Prototype]]null \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype-null@2x.png b/1-js/08-prototypes/03-native-prototypes/object-prototype-null@2x.png deleted file mode 100644 index d97efa884..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype-null@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype.png b/1-js/08-prototypes/03-native-prototypes/object-prototype.png deleted file mode 100644 index 820ffcc73..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype.svg b/1-js/08-prototypes/03-native-prototypes/object-prototype.svg new file mode 100644 index 000000000..8d3d0beee --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/object-prototype.svg @@ -0,0 +1 @@ +constructor: Object toString: function ...Object.prototypeObjectprototype \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/object-prototype@2x.png b/1-js/08-prototypes/03-native-prototypes/object-prototype@2x.png deleted file mode 100644 index 1eb7e8749..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/object-prototype@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.png b/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.png deleted file mode 100644 index 4b381460a..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.svg b/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.svg new file mode 100644 index 000000000..3489ecdd8 --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit.svg @@ -0,0 +1 @@ +eats: truename: "White Rabbit"animalRabbitrabbit[[Prototype]]prototype \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit@2x.png b/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit@2x.png deleted file mode 100644 index c6e6ab5f6..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/proto-constructor-animal-rabbit@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.png b/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.png deleted file mode 100644 index 8f3519a74..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.png and /dev/null differ diff --git a/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.svg b/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.svg new file mode 100644 index 000000000..3e11f275b --- /dev/null +++ b/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor.svg @@ -0,0 +1 @@ +default "prototype"Rabbitrabbit[[Prototype]]prototypeconstructor \ No newline at end of file diff --git a/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor@2x.png b/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor@2x.png deleted file mode 100644 index 07acb8f4a..000000000 Binary files a/1-js/08-prototypes/03-native-prototypes/rabbit-prototype-constructor@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/04-prototype-methods/article.md b/1-js/08-prototypes/04-prototype-methods/article.md index a9c21faaf..8a71dbf1c 100644 --- a/1-js/08-prototypes/04-prototype-methods/article.md +++ b/1-js/08-prototypes/04-prototype-methods/article.md @@ -26,6 +26,7 @@ let rabbit = Object.create(animal); */!* alert(rabbit.eats); // true + *!* alert(Object.getPrototypeOf(rabbit) === animal); // get the prototype of rabbit */!* @@ -78,13 +79,13 @@ As of now we have all these ways at our disposal. Why was `__proto__` replaced by the functions `getPrototypeOf/setPrototypeOf`? That's an interesting question, requiring us to understand why `__proto__` is bad. Read on to get the answer. -```warn header="Don't reset `[[Prototype]]` unless the speed doesn't matter" +```warn header="Don't change `[[Prototype]]` on existing objects if speed matters" Technically, we can get/set `[[Prototype]]` at any time. But usually we only set it once at the object creation time, and then do not modify: `rabbit` inherits from `animal`, and that is not going to change. And JavaScript engines are highly optimized to that. Changing a prototype "on-the-fly" with `Object.setPrototypeOf` or `obj.__proto__=` is a very slow operation, it breaks internal optimizations for object property access operations. So evade it unless you know what you're doing, or JavaScript speed totally doesn't matter for you. ``` -## "Very plain" objects +## "Very plain" objects [#very-plain] As we know, objects can be used as associative arrays to store key/value pairs. @@ -111,7 +112,7 @@ Here the consequences are not terrible. But in other cases, we may be assigning What's worst -- usually developers do not think about such possibility at all. That makes such bugs hard to notice and even turn them into vulnerabilities, especially when JavaScript is used on server-side. -Unexpected things also may happen when accessing `toString` property -- that's a function by default, and other built-in properties. +Unexpected things also may happen when assigning to `toString` -- that's a function by default, and other built-in methods. How to evade the problem? @@ -121,7 +122,7 @@ But `Object` also can serve us well here, because language creators gave a thoug The `__proto__` is not a property of an object, but an accessor property of `Object.prototype`: -![](object-prototype-2.png) +![](object-prototype-2.svg) So, if `obj.__proto__` is read or set, the corresponding getter/setter is called from its prototype, and it gets/sets `[[Prototype]]`. @@ -142,7 +143,7 @@ alert(obj[key]); // "some value" `Object.create(null)` creates an empty object without a prototype (`[[Prototype]]` is `null`): -![](object-prototype-null.png) +![](object-prototype-null.svg) So, there is no inherited getter/setter for `__proto__`. Now it is processed as a regular data property, so the example above works right. @@ -160,7 +161,7 @@ alert(obj); // Error (no toString) ...But that's usually fine for associative arrays. -Please note that most object-related methods are `Object.something(...)`, like `Object.keys(obj)` -- they are not in the prototype, so they will keep working on such objects: +Note that most object-related methods are `Object.something(...)`, like `Object.keys(obj)` -- they are not in the prototype, so they will keep working on such objects: ```js run @@ -179,7 +180,7 @@ Modern methods to setup and directly access the prototype are: - [Object.getPrototypeOf(obj)](mdn:js/Object.getPrototypeOf) -- returns the `[[Prototype]]` of `obj` (same as `__proto__` getter). - [Object.setPrototypeOf(obj, proto)](mdn:js/Object.setPrototypeOf) -- sets the `[[Prototype]]` of `obj` to `proto` (same as `__proto__` setter). -The built-in `__proto__` getter/setter is unsafe if we'd want to put user-generated keys in to an object. Just because a user may enter "__proto__" as the key, and there'll be an error with hopefully easy, but generally unpredictable consequences. +The built-in `__proto__` getter/setter is unsafe if we'd want to put user-generated keys in to an object. Just because a user may enter `"__proto__"` as the key, and there'll be an error, with hopefully light, but generally unpredictable consequences. So we can either use `Object.create(null)` to create a "very plain" object without `__proto__`, or stick to `Map` objects for that. @@ -189,15 +190,16 @@ Also, `Object.create` provides an easy way to shallow-copy an object with all de let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); ``` +We also made it clear that `__proto__` is a getter/setter for `[[Prototype]]` and resides in `Object.prototype`, just as other methods. + +We can create an object without a prototype by `Object.create(null)`. Such objects are used as "pure dictionaries", they have no issues with `"__proto__"` as the key. + +Other methods: - [Object.keys(obj)](mdn:js/Object/keys) / [Object.values(obj)](mdn:js/Object/values) / [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of enumerable own string property names/values/key-value pairs. - [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) -- returns an array of all own symbolic keys. - [Object.getOwnPropertyNames(obj)](mdn:js/Object/getOwnPropertyNames) -- returns an array of all own string keys. - [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) -- returns an array of all own keys. -- [obj.hasOwnProperty(key)](mdn:js/Object/hasOwnProperty): it returns `true` if `obj` has its own (not inherited) keytt named `key`. - -We also made it clear that `__proto__` is a getter/setter for `[[Prototype]]` and resides in `Object.prototype`, just as other methods. - -We can create an object without a prototype by `Object.create(null)`. Such objects are used as "pure dictionaries", they have no issues with `"__proto__"` as the key. +- [obj.hasOwnProperty(key)](mdn:js/Object/hasOwnProperty): it returns `true` if `obj` has its own (not inherited) key named `key`. All methods that return object properties (like `Object.keys` and others) -- return "own" properties. If we want inherited ones, then we can use `for..in`. diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-2.png b/1-js/08-prototypes/04-prototype-methods/object-prototype-2.png deleted file mode 100644 index 343435af6..000000000 Binary files a/1-js/08-prototypes/04-prototype-methods/object-prototype-2.png and /dev/null differ diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-2.svg b/1-js/08-prototypes/04-prototype-methods/object-prototype-2.svg new file mode 100644 index 000000000..86d09ae0d --- /dev/null +++ b/1-js/08-prototypes/04-prototype-methods/object-prototype-2.svg @@ -0,0 +1 @@ +... get __proto__: function set __proto__: functionObject.prototypeObjectobj[[Prototype]]prototype \ No newline at end of file diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-2@2x.png b/1-js/08-prototypes/04-prototype-methods/object-prototype-2@2x.png deleted file mode 100644 index 86b8a678e..000000000 Binary files a/1-js/08-prototypes/04-prototype-methods/object-prototype-2@2x.png and /dev/null differ diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-null.png b/1-js/08-prototypes/04-prototype-methods/object-prototype-null.png deleted file mode 100644 index 792c4f423..000000000 Binary files a/1-js/08-prototypes/04-prototype-methods/object-prototype-null.png and /dev/null differ diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-null.svg b/1-js/08-prototypes/04-prototype-methods/object-prototype-null.svg new file mode 100644 index 000000000..858f8317e --- /dev/null +++ b/1-js/08-prototypes/04-prototype-methods/object-prototype-null.svg @@ -0,0 +1 @@ +obj[[Prototype]]null \ No newline at end of file diff --git a/1-js/08-prototypes/04-prototype-methods/object-prototype-null@2x.png b/1-js/08-prototypes/04-prototype-methods/object-prototype-null@2x.png deleted file mode 100644 index d97efa884..000000000 Binary files a/1-js/08-prototypes/04-prototype-methods/object-prototype-null@2x.png and /dev/null differ diff --git a/1-js/09-classes/01-class/article.md b/1-js/09-classes/01-class/article.md index 30a958df7..3cfcd4cb3 100644 --- a/1-js/09-classes/01-class/article.md +++ b/1-js/09-classes/01-class/article.md @@ -25,7 +25,7 @@ class MyClass { } ``` -Then `new MyClass()` creates a new object with all the listed methods. +Then use `new MyClass()` to create a new object with all the listed methods. The `constructor()` method is called automatically by `new`, so we can initialize the object there. @@ -53,7 +53,7 @@ When `new User("John")` is called: 1. A new object is created. 2. The `constructor` runs with the given argument and assigns `this.name` to it. -...Then we can call methods, such as `user.sayHi`. +...Then we can call object methods, such as `user.sayHi()`. ```warn header="No comma between class methods" @@ -85,19 +85,18 @@ alert(typeof User); // function ``` What `class User {...}` construct really does is: -1. Creates a function named `User`, that becomes the result of the class declaration. - - The function code is taken from the `constructor` method (assumed empty if we don't write such method). -3. Stores all methods, such as `sayHi`, in `User.prototype`. -Afterwards, for new objects, when we call a method, it's taken from the prototype, just as described in the chapter . So `new User` object has access to class methods. +1. Creates a function named `User`, that becomes the result of the class declaration. The function code is taken from the `constructor` method (assumed empty if we don't write such method). +2. Stores class methods, such as `sayHi`, in `User.prototype`. + +Afterwards, for `new User` objects, when we call a method, it's taken from the prototype, just as described in the chapter . So the object has access to class methods. We can illustrate the result of `class User` declaration as: -![](class-user.png) +![](class-user.svg) Here's the code to introspect it: - ```js run class User { constructor(name) { this.name = name; } @@ -119,7 +118,7 @@ alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi ## Not just a syntax sugar -Sometimes people say that `class` is a "syntax sugar" in JavaScript, because we could actually declare the same without `class` keyword at all: +Sometimes people say that `class` is a "syntax sugar" (syntax that is designed to make things easier to read, but doesn't introduce anything new), because we could actually declare the same without `class` keyword at all: ```js run // rewriting class User in pure functions @@ -147,7 +146,7 @@ Although, there are important differences. 1. First, a function created by `class` is labelled by a special internal property `[[FunctionKind]]:"classConstructor"`. So it's not entirely the same as creating it manually. - Unlike a regular function, a class constructor can't be called without `new`: + Unlike a regular function, a class constructor must be called with `new`: ```js run class User { @@ -176,8 +175,7 @@ Although, there are important differences. 3. Classes always `use strict`. All code inside the class construct is automatically in strict mode. - -Also, in addition to its basic operation, the `class` syntax brings many other features with it which we'll explore later. +Besides, `class` syntax brings many other features that we'll explore later. ## Class Expression @@ -193,7 +191,7 @@ let User = class { }; ``` -Similar to Named Function Expressions, class expressions may or may not have a name. +Similar to Named Function Expressions, class expressions may have a name. If a class expression has a name, it's visible inside the class only: @@ -202,13 +200,13 @@ If a class expression has a name, it's visible inside the class only: // (no such term in the spec, but that's similar to Named Function Expression) let User = class *!*MyClass*/!* { sayHi() { - alert(MyClass); // MyClass is visible only inside the class + alert(MyClass); // MyClass name is visible only inside the class } }; new User().sayHi(); // works, shows MyClass definition -alert(MyClass); // error, MyClass not visible outside of the class +alert(MyClass); // error, MyClass name isn't visible outside of the class ``` @@ -284,13 +282,14 @@ Object.defineProperties(User.prototype, { }); ``` -Here's an example with computed properties: +Here's an example with a computed property in brackets `[...]`: ```js run -function f() { return "sayHi"; } - class User { - [f()]() { + +*!* + ['say' + 'Hi']() { +*/!* alert("Hello"); } @@ -311,7 +310,9 @@ In the example above, `User` only had methods. Let's add a property: ```js run class User { +*!* name = "Anonymous"; +*/!* sayHi() { alert(`Hello, ${this.name}!`); @@ -321,8 +322,7 @@ class User { new User().sayHi(); ``` -The property is not placed into `User.prototype`. Instead, it is created by `new`, separately for every object. So, the property will never be shared between different objects of the same class. - +The property `name` is not placed into `User.prototype`. Instead, it is created by `new` before calling constructor, it's the property of the object itself. ## Summary @@ -330,7 +330,7 @@ The basic class syntax looks like this: ```js class MyClass { - prop = value; // field + prop = value; // property constructor(...) { // constructor // ... @@ -341,7 +341,7 @@ class MyClass { get something(...) {} // getter method set something(...) {} // setter method - [Symbol.iterator]() {} // method with computed name/symbol name + [Symbol.iterator]() {} // method with computed name (symbol here) // ... } ``` diff --git a/1-js/09-classes/01-class/class-user.png b/1-js/09-classes/01-class/class-user.png deleted file mode 100644 index dc8b75679..000000000 Binary files a/1-js/09-classes/01-class/class-user.png and /dev/null differ diff --git a/1-js/09-classes/01-class/class-user.svg b/1-js/09-classes/01-class/class-user.svg new file mode 100644 index 000000000..5ac0146a6 --- /dev/null +++ b/1-js/09-classes/01-class/class-user.svg @@ -0,0 +1 @@ +sayHi: functionUserUser.prototypeprototypeconstructor: User \ No newline at end of file diff --git a/1-js/09-classes/01-class/class-user@2x.png b/1-js/09-classes/01-class/class-user@2x.png deleted file mode 100644 index aaa53708f..000000000 Binary files a/1-js/09-classes/01-class/class-user@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.png b/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.png deleted file mode 100644 index c610e28c3..000000000 Binary files a/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.svg b/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.svg new file mode 100644 index 000000000..0a1f4382c --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object.svg @@ -0,0 +1 @@ +call: function bind: function ...Function.prototypeconstructorObjectRabbit[[Prototype]][[Prototype]]constructorcall: function bind: function ...Function.prototypeRabbit[[Prototype]]constructorclass Rabbitclass Rabbit extends Object \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object@2x.png b/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object@2x.png deleted file mode 100644 index 4819c7f79..000000000 Binary files a/1-js/09-classes/02-class-inheritance/3-class-extend-object/rabbit-extends-object@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/3-class-extend-object/solution.md b/1-js/09-classes/02-class-inheritance/3-class-extend-object/solution.md index c1483aa36..fa26ec834 100644 --- a/1-js/09-classes/02-class-inheritance/3-class-extend-object/solution.md +++ b/1-js/09-classes/02-class-inheritance/3-class-extend-object/solution.md @@ -71,7 +71,7 @@ By the way, `Function.prototype` has "generic" function methods, like `call`, `b Here's the picture: -![](rabbit-extends-object.png) +![](rabbit-extends-object.svg) So, to put it short, there are two differences: diff --git a/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.png b/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.png deleted file mode 100644 index 0d887dbc0..000000000 Binary files a/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.svg b/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.svg new file mode 100644 index 000000000..3412d9825 --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/animal-rabbit-extends.svg @@ -0,0 +1 @@ +constructor: Animal run: function stop: functionAnimal.prototypeconstructor: Rabbit hide: functionRabbit.prototypeAnimalRabbitnew Rabbit[[Prototype]][[Prototype]]prototypeprototypename: "White Rabbit"constructorconstructor \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/animal-rabbit-extends@2x.png b/1-js/09-classes/02-class-inheritance/animal-rabbit-extends@2x.png deleted file mode 100644 index af09271a9..000000000 Binary files a/1-js/09-classes/02-class-inheritance/animal-rabbit-extends@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/article.md b/1-js/09-classes/02-class-inheritance/article.md index abb7d1e33..108cc11f2 100644 --- a/1-js/09-classes/02-class-inheritance/article.md +++ b/1-js/09-classes/02-class-inheritance/article.md @@ -17,14 +17,14 @@ class Animal { } stop() { this.speed = 0; - alert(`${this.name} stopped.`); + alert(`${this.name} stands still.`); } } let animal = new Animal("My animal"); ``` -![](rabbit-animal-independent-animal.png) +![](rabbit-animal-independent-animal.svg) ...And `Rabbit`: @@ -42,7 +42,7 @@ class Rabbit { let rabbit = new Rabbit("My rabbit"); ``` -![](rabbit-animal-independent-rabbit.png) +![](rabbit-animal-independent-rabbit.svg) Right now they are fully independent. @@ -65,7 +65,7 @@ class Animal { } stop() { this.speed = 0; - alert(`${this.name} stopped.`); + alert(`${this.name} stands still.`); } } @@ -88,11 +88,11 @@ Now the `Rabbit` code became a bit shorter, as it uses `Animal` constructor by d Internally, `extends` keyword adds `[[Prototype]]` reference from `Rabbit.prototype` to `Animal.prototype`: -![](animal-rabbit-extends.png) +![](animal-rabbit-extends.svg) So, if a method is not found in `Rabbit.prototype`, JavaScript takes it from `Animal.prototype`. -As we can recall from the chapter , JavaScript uses the same prototypal inheritance for build-in objects. E.g. `Date.prototype.[[Prototype]]` is `Object.prototype`, so dates have generic object methods. +As we can recall from the chapter , JavaScript uses prototypal inheritance for build-in objects. E.g. `Date.prototype.[[Prototype]]` is `Object.prototype`, so dates have generic object methods. ````smart header="Any expression is allowed after `extends`" Class syntax allows to specify not just a class, but any expression after `extends`. @@ -131,7 +131,6 @@ class Rabbit extends Animal { } ``` - ...But usually we don't want to totally replace a parent method, but rather to build on top of it, tweak or extend its functionality. We do something in our method, but call the parent method before/after it or in the process. Classes provide `"super"` keyword for that. @@ -156,7 +155,7 @@ class Animal { stop() { this.speed = 0; - alert(`${this.name} stopped.`); + alert(`${this.name} stands still.`); } } @@ -177,7 +176,7 @@ class Rabbit extends Animal { let rabbit = new Rabbit("White Rabbit"); rabbit.run(5); // White Rabbit runs with speed 5. -rabbit.stop(); // White Rabbit stopped. White rabbit hides! +rabbit.stop(); // White Rabbit stands still. White rabbit hides! ``` Now `Rabbit` has the `stop` method that calls the parent `super.stop()` in the process. @@ -266,12 +265,12 @@ In JavaScript, there's a distinction between a "constructor function of an inher The difference is: -- When a normal constructor runs, it creates an empty object as `this` and continues with it. -- But when a derived constructor runs, it doesn't do it. It expects the parent constructor to do this job. +- When a normal constructor runs, it creates an empty object and assigns it to `this`. +- But when a derived constructor runs, it doesn't do this. It expects the parent constructor to do this job. -So if we're making a constructor of our own, then we must call `super`, because otherwise the object with `this` reference to it won't be created. And we'll get an error. +So if we're making a constructor of our own, then we must call `super`, because otherwise the object for `this` won't be created. And we'll get an error. -For `Rabbit` to work, we need to call `super()` before using `this`, like here: +For `Rabbit` constructor to work, it needs to call `super()` before using `this`, like here: ```js run class Animal { @@ -307,16 +306,24 @@ alert(rabbit.earLength); // 10 ## Super: internals, [[HomeObject]] +```warn header="Advanced information" +If you're reading the tutorial for the first time - this section may be skipped. + +It's about the internal mechanisms behind inheritance and `super`. +``` + Let's get a little deeper under the hood of `super`. We'll see some interesting things by the way. First to say, from all that we've learned till now, it's impossible for `super` to work at all! -Yeah, indeed, let's ask ourselves, how it could technically work? When an object method runs, it gets the current object as `this`. If we call `super.method()` then, it needs to retrieve the `method` from the prototype of the current object. +Yeah, indeed, let's ask ourselves, how it should technically work? When an object method runs, it gets the current object as `this`. If we call `super.method()` then, the engine needs to get the `method` from the prototype of the current object. But how? The task may seem simple, but it isn't. The engine knows the current object `this`, so it could get the parent `method` as `this.__proto__.method`. Unfortunately, such a "naive" solution won't work. Let's demonstrate the problem. Without classes, using plain objects for the sake of simplicity. +You may skip this part and go below to the `[[HomeObject]]` subsection if you don't want to know the details. That won't harm. Or read on if you're interested in understanding things in-depth. + In the example below, `rabbit.__proto__ = animal`. Now let's try: in `rabbit.eat()` we'll call `animal.eat()`, using `this.__proto__`: ```js run @@ -384,7 +391,7 @@ So, in both lines `(*)` and `(**)` the value of `this.__proto__` is exactly the Here's the picture of what happens: -![](this-super-loop.png) +![](this-super-loop.svg) 1. Inside `longEar.eat()`, the line `(**)` calls `rabbit.eat` providing it with `this=longEar`. ```js @@ -460,7 +467,7 @@ The very existance of `[[HomeObject]]` violates that principle, because methods The only place in the language where `[[HomeObject]]` is used -- is `super`. So, if a method does not use `super`, then we can still consider it free and copy between objects. But with `super` things may go wrong. -Here's the demo of a wrong `super` call: +Here's the demo of a wrong `super` result after copying: ```js run let animal = { @@ -469,6 +476,7 @@ let animal = { } }; +// rabbit inherits from animal let rabbit = { __proto__: animal, sayHi() { @@ -482,6 +490,7 @@ let plant = { } }; +// tree inherits from plant let tree = { __proto__: plant, *!* @@ -498,10 +507,12 @@ A call to `tree.sayHi()` shows "I'm an animal". Definitevely wrong. The reason is simple: - In the line `(*)`, the method `tree.sayHi` was copied from `rabbit`. Maybe we just wanted to avoid code duplication? -- So its `[[HomeObject]]` is `rabbit`, as it was created in `rabbit`. There's no way to change `[[HomeObject]]`. +- Its `[[HomeObject]]` is `rabbit`, as it was created in `rabbit`. There's no way to change `[[HomeObject]]`. - The code of `tree.sayHi()` has `super.sayHi()` inside. It goes up from `rabbit` and takes the method from `animal`. -![](super-homeobject-wrong.png) +Here's the diagram of what happens: + +![](super-homeobject-wrong.svg) ### Methods, not function properties diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.png b/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.png deleted file mode 100644 index 8d30622ce..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.svg b/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.svg new file mode 100644 index 000000000..546aa334f --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/class-inheritance-array-object.svg @@ -0,0 +1 @@ +slice: function ...Array.prototypearrhasOwnProperty: function ...Object.prototype[1, 2, 3][[Prototype]][[Prototype]] \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-array-object@2x.png b/1-js/09-classes/02-class-inheritance/class-inheritance-array-object@2x.png deleted file mode 100644 index 00f6bd80d..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-array-object@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.png deleted file mode 100644 index f8afbbcd6..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.svg b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.svg new file mode 100644 index 000000000..3bdda5a02 --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2.svg @@ -0,0 +1 @@ +jump: functionRabbit.prototyperabbiteat: functionAnimal.prototypename: "White Rabbit"[[Prototype]][[Prototype]]Rabbit.prototype.__proto__ = Animal.prototype sets thistoString: function hasOwnProperty: function ...Object.prototype[[Prototype]][[Prototype]]null \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2@2x.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2@2x.png deleted file mode 100644 index cf5aa6554..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal-2@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.png deleted file mode 100644 index a6f8964e6..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.svg b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.svg new file mode 100644 index 000000000..91f82896d --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal.svg @@ -0,0 +1 @@ +methods of RabbitRabbit.prototyperabbitmethods of AnimalAnimal.prototype[[Prototype]][[Prototype]]properties of rabbit \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal@2x.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal@2x.png deleted file mode 100644 index 2e3f4d7ff..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-animal@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal.png deleted file mode 100644 index 387975a9c..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal@2x.png b/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal@2x.png deleted file mode 100644 index ca7313593..000000000 Binary files a/1-js/09-classes/02-class-inheritance/class-inheritance-rabbit-run-animal@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.png b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.png deleted file mode 100644 index 79351a754..000000000 Binary files a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.svg b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.svg new file mode 100644 index 000000000..bf86db77d --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal.svg @@ -0,0 +1 @@ + constructor: Animal run: function stop: functionAnimal.prototypeAnimalnew Animal[[Prototype]]prototypename: "My animal" \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal@2x.png b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal@2x.png deleted file mode 100644 index 346574e0c..000000000 Binary files a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-animal@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.png b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.png deleted file mode 100644 index 3d3b78cca..000000000 Binary files a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.svg b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.svg new file mode 100644 index 000000000..8a5e25037 --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit.svg @@ -0,0 +1 @@ + constructor: Rabbit hide: functionRabbit.prototypeRabbitnew Rabbit[[Prototype]]prototypename: "My rabbit" \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit@2x.png b/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit@2x.png deleted file mode 100644 index a923d10e5..000000000 Binary files a/1-js/09-classes/02-class-inheritance/rabbit-animal-independent-rabbit@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.png b/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.png deleted file mode 100644 index 30f4d9128..000000000 Binary files a/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.svg b/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.svg new file mode 100644 index 000000000..c9c8fea9e --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/super-homeobject-wrong.svg @@ -0,0 +1 @@ +sayHiplantsayHitreesayHianimalrabbit[[HomeObject]]sayHi \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/super-homeobject-wrong@2x.png b/1-js/09-classes/02-class-inheritance/super-homeobject-wrong@2x.png deleted file mode 100644 index e7fd103f4..000000000 Binary files a/1-js/09-classes/02-class-inheritance/super-homeobject-wrong@2x.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/this-super-loop.png b/1-js/09-classes/02-class-inheritance/this-super-loop.png deleted file mode 100644 index e68ed70e7..000000000 Binary files a/1-js/09-classes/02-class-inheritance/this-super-loop.png and /dev/null differ diff --git a/1-js/09-classes/02-class-inheritance/this-super-loop.svg b/1-js/09-classes/02-class-inheritance/this-super-loop.svg new file mode 100644 index 000000000..342574da9 --- /dev/null +++ b/1-js/09-classes/02-class-inheritance/this-super-loop.svg @@ -0,0 +1 @@ +rabbitlongEarrabbitlongEar \ No newline at end of file diff --git a/1-js/09-classes/02-class-inheritance/this-super-loop@2x.png b/1-js/09-classes/02-class-inheritance/this-super-loop@2x.png deleted file mode 100644 index 037d07587..000000000 Binary files a/1-js/09-classes/02-class-inheritance/this-super-loop@2x.png and /dev/null differ diff --git a/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.png b/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.png deleted file mode 100644 index c5e7e3e49..000000000 Binary files a/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.png and /dev/null differ diff --git a/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.svg b/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.svg new file mode 100644 index 000000000..fab401df6 --- /dev/null +++ b/1-js/09-classes/03-static-properties-methods/animal-rabbit-static.svg @@ -0,0 +1 @@ +constructor: Animal run: functionAnimal.prototypeconstructor: Rabbit hide: functionRabbit.prototypeAnimalRabbitrabbit[[Prototype]][[Prototype]][[Prototype]]prototypeprototypecomparename: "White Rabbit" \ No newline at end of file diff --git a/1-js/09-classes/03-static-properties-methods/animal-rabbit-static@2x.png b/1-js/09-classes/03-static-properties-methods/animal-rabbit-static@2x.png deleted file mode 100644 index de434af2c..000000000 Binary files a/1-js/09-classes/03-static-properties-methods/animal-rabbit-static@2x.png and /dev/null differ diff --git a/1-js/09-classes/03-static-properties-methods/article.md b/1-js/09-classes/03-static-properties-methods/article.md index b940e04c8..583fabcff 100644 --- a/1-js/09-classes/03-static-properties-methods/article.md +++ b/1-js/09-classes/03-static-properties-methods/article.md @@ -1,9 +1,9 @@ # Static properties and methods -We can also assign a method to the class function, not to its `"prototype"`. Such methods are called *static*. +We can also assign a method to the class function itself, not to its `"prototype"`. Such methods are called *static*. -An example: +In a class, they are prepended by `static` keyword, like this: ```js run class User { @@ -17,21 +17,21 @@ class User { User.staticMethod(); // true ``` -That actually does the same as assigning it as a function property: +That actually does the same as assigning it as a property directly: ```js -function User() { } +class User() { } User.staticMethod = function() { alert(this === User); }; ``` -The value of `this` inside `User.staticMethod()` is the class constructor `User` itself (the "object before dot" rule). +The value of `this` in `User.staticMethod()` call is the class constructor `User` itself (the "object before dot" rule). Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it. -For instance, we have `Article` objects and need a function to compare them. The natural choice would be `Article.compare`, like this: +For instance, we have `Article` objects and need a function to compare them. A natural solution would be to add `Article.compare` method, like this: ```js run class Article { @@ -61,13 +61,13 @@ articles.sort(Article.compare); alert( articles[0].title ); // CSS ``` -Here `Article.compare` stands "over" the articles, as a means to compare them. It's not a method of an article, but rather of the whole class. +Here `Article.compare` stands "above" articles, as a means to compare them. It's not a method of an article, but rather of the whole class. Another example would be a so-called "factory" method. Imagine, we need few ways to create an article: 1. Create by given parameters (`title`, `date` etc). 2. Create an empty article with today's date. -3. ... +3. ...or else somehow. The first way can be implemented by the constructor. And for the second one we can make a static method of the class. @@ -90,7 +90,7 @@ class Article { let article = Article.createTodays(); -alert( article.title ); // Todays digest +alert( article.title ); // Today's digest ``` Now every time we need to create a today's digest, we can call `Article.createTodays()`. Once again, that's not a method of an article, but a method of the whole class. @@ -107,7 +107,7 @@ Article.remove({id: 12345}); [recent browser=Chrome] -Static properties are also possible, just like regular class properties: +Static properties are also possible, they look like regular class properties, but prepended by `static`: ```js run class Article { @@ -123,9 +123,9 @@ That is the same as a direct assignment to `Article`: Article.publisher = "Ilya Kantor"; ``` -## Statics and inheritance +## Inheritance of static methods -Statics are inherited, we can access `Parent.method` as `Child.method`. +Static methods are inherited. For instance, `Animal.compare` in the code below is inherited and accessible as `Rabbit.compare`: @@ -169,36 +169,39 @@ rabbits.sort(Rabbit.compare); rabbits[0].run(); // Black Rabbit runs with speed 5. ``` -Now we can call `Rabbit.compare` assuming that the inherited `Animal.compare` will be called. +Now when we can call `Rabbit.compare`, the inherited `Animal.compare` will be called. How does it work? Again, using prototypes. As you might have already guessed, `extends` gives `Rabbit` the `[[Prototype]]` reference to `Animal`. +![](animal-rabbit-static.svg) -![](animal-rabbit-static.png) +So, `Rabbit extends Animal` creates two `[[Prototype]]` references: -So, `Rabbit` function now inherits from `Animal` function. And `Animal` function normally has `[[Prototype]]` referencing `Function.prototype`, because it doesn't `extend` anything. +1. `Rabbit` function prototypally inherits from `Animal` function. +2. `Rabbit.prototype` prototypally inherits from `Animal.prototype`. -Here, let's check that: +As the result, inheritance works both for regular and static methods. + +Here, let's check that by code: ```js run class Animal {} class Rabbit extends Animal {} -// for static properties and methods +// for statics alert(Rabbit.__proto__ === Animal); // true -// the next step up leads to Function.prototype -alert(Animal.__proto__ === Function.prototype); // true - -// the "normal" prototype chain for object methods +// for regular methods alert(Rabbit.prototype.__proto__ === Animal.prototype); ``` -This way `Rabbit` has access to all static methods of `Animal`. - ## Summary -Static methods are used for the functionality that doesn't relate to a concrete class instance, doesn't require an instance to exist, but rather belongs to the class as a whole, like `Article.compare` -- a generic method to compare two articles. +Static methods are used for the functionality that belongs to the class "as a whole", doesn't relate to a concrete class instance. + +For example, a method for comparison `Article.compare(article1, article2)` or a factory method `Article.createTodays()`. + +They are labeled by the word `static` in class declaration. Static properties are used when we'd like to store class-level data, also not bound to an instance. @@ -214,13 +217,13 @@ class MyClass { } ``` -That's technically the same as assigning to the class itself: +Technically, static declaration is the same as assigning to the class itself: ```js MyClass.property = ... MyClass.method = ... ``` -Static properties are inherited. +Static properties and methods are inherited. -Technically, for `class B extends A` the prototype of the class `B` itself points to `A`: `B.[[Prototype]] = A`. So if a field is not found in `B`, the search continues in `A`. +For `class B extends A` the prototype of the class `B` itself points to `A`: `B.[[Prototype]] = A`. So if a field is not found in `B`, the search continues in `A`. diff --git a/1-js/09-classes/04-private-protected-properties-methods/article.md b/1-js/09-classes/04-private-protected-properties-methods/article.md index 13bf03595..ef0d497a8 100644 --- a/1-js/09-classes/04-private-protected-properties-methods/article.md +++ b/1-js/09-classes/04-private-protected-properties-methods/article.md @@ -48,16 +48,16 @@ So, all we need to use an object is to know its external interface. We may be co That was a general introduction. -In JavaScript, there are three types of properties and members: +In JavaScript, there are two types of object fields (properties and methods): - Public: accessible from anywhere. They comprise the external interface. Till now we were only using public properties and methods. - Private: accessible only from inside the class. These are for the internal interface. -In many other languages there also exist "protected" fields: accessible only from inside the class and those extending it. They are also useful for the internal interface. They are in a sense more widespread than private ones, because we usually want inheriting classes to gain access to properly do the extension. +In many other languages there also exist "protected" fields: accessible only from inside the class and those extending it (like private, but plus access from inheriting classes). They are also useful for the internal interface. They are in a sense more widespread than private ones, because we usually want inheriting classes to gain access to them. Protected fields are not implemented in JavaScript on the language level, but in practice they are very convenient, so they are emulated. -In the next step we'll make a coffee machine in JavaScript with all these types of properties. A coffee machine has a lot of details, we won't model them to stay simple (though we could). +Now we'll make a coffee machine in JavaScript with all these types of properties. A coffee machine has a lot of details, we won't model them to stay simple (though we could). ## Protecting "waterAmount" @@ -87,7 +87,7 @@ Let's change `waterAmount` property to protected to have more control over it. F **Protected properties are usually prefixed with an underscore `_`.** -That is not enforced on the language level, but there's a convention that such properties and methods should not be accessed from the outside. Most programmers follow it. +That is not enforced on the language level, but there's a well-known convention between programmers that such properties and methods should not be accessed from the outside. So our property will be called `_waterAmount`: @@ -171,9 +171,9 @@ class CoffeeMachine { new CoffeeMachine().setWaterAmount(100); ``` -That looks a bit longer, but functions are more flexible. They can accept multiple arguments (even if we don't need them right now). So, for the future, just in case we need to refactor something, functions are a safer choice. +That looks a bit longer, but functions are more flexible. They can accept multiple arguments (even if we don't need them right now). -Surely, there's a tradeoff. On the other hand, get/set syntax is shorter, so ultimately there's no strict rule, it's up to you to decide. +On the other hand, get/set syntax is shorter, so ultimately there's no strict rule, it's up to you to decide. ```` ```smart header="Protected fields are inherited" @@ -190,9 +190,9 @@ There's a finished JavaScript proposal, almost in the standard, that provides la Privates should start with `#`. They are only accessible from inside the class. -For instance, here we add a private `#waterLimit` property and extract the water-checking logic into a separate method: +For instance, here's a private `#waterLimit` property and the water-checking private method `#checkWater`: -```js +```js run class CoffeeMachine { *!* #waterLimit = 200; @@ -205,29 +205,15 @@ class CoffeeMachine { } */!* - _waterAmount = 0; - - set waterAmount(value) { -*!* - this.#checkWater(value); -*/!* - this._waterAmount = value; - } - - get waterAmount() { - return this._waterAmount; - } - } let coffeeMachine = new CoffeeMachine(); *!* +// can't access privates from outside of the class coffeeMachine.#checkWater(); // Error coffeeMachine.#waterLimit = 1000; // Error */!* - -coffeeMachine.waterAmount = 100; // Works ``` On the language level, `#` is a special sign that the field is private. We can't access it from outside or from inheriting classes. @@ -271,19 +257,19 @@ class MegaCoffeeMachine extends CoffeeMachine() { } ``` -In many scenarios such limitation is too severe. If we extend a `CoffeeMachine`, we may have legitimate reason to access its internals. That's why protected fields are used most of the time, even though they are not supported by the language syntax. +In many scenarios such limitation is too severe. If we extend a `CoffeeMachine`, we may have legitimate reason to access its internals. That's why protected fields are used more often, even though they are not supported by the language syntax. -````warn +````warn header="Private fields are not available as this[name]" Private fields are special. -Remember, usually we can access fields by this[name]: +As we know, usually we can access fields using `this[name]`: ```js class User { ... sayHi() { let fieldName = "name"; - alert(`Hello, ${this[fieldName]}`); + alert(`Hello, ${*!*this[fieldName]*/!*}`); } } ``` @@ -309,11 +295,11 @@ Protection for users, so that they don't shoot themselves in the feet Supportable : The situation in programming is more complex than with a real-life coffee machine, because we don't just buy it once. The code constantly undergoes development and improvement. - **If we strictly delimit the internal interface, then the developer of the class can freely change its internal properties and methods, even without informing the users..** + **If we strictly delimit the internal interface, then the developer of the class can freely change its internal properties and methods, even without informing the users.** - It's much easier to develop, if you know that certain methods can be renamed, their parameters can be changed, and even removed, because no external code depends on them. + If you're a developer of such class, it's great to know that private methods can be safely renamed, their parameters can be changed, and even removed, because no external code depends on them. - For users, when a new version comes out, it may be a total overhaul, but still simple to upgrade if the external interface is the same. + For users, when a new version comes out, it may be a total overhaul internally, but still simple to upgrade if the external interface is the same. Hiding complexity : People adore to use things that are simple. At least from outside. What's inside is a different thing. diff --git a/1-js/09-classes/05-extend-natives/article.md b/1-js/09-classes/05-extend-natives/article.md index f85aa0242..2dc4902b5 100644 --- a/1-js/09-classes/05-extend-natives/article.md +++ b/1-js/09-classes/05-extend-natives/article.md @@ -21,20 +21,20 @@ alert(filteredArr); // 10, 50 alert(filteredArr.isEmpty()); // false ``` -Please note a very interesting thing. Built-in methods like `filter`, `map` and others -- return new objects of exactly the inherited type. They rely on the `constructor` property to do so. +Please note a very interesting thing. Built-in methods like `filter`, `map` and others -- return new objects of exactly the inherited type `PowerArray`. Their internal implementation uses object `constructor` property for that. In the example above, ```js arr.constructor === PowerArray ``` -So when `arr.filter()` is called, it internally creates the new array of results using exactly `new PowerArray`, not basic `Array`. That's actually very cool, because we can keep using `PowerArray` methods further on the result. +When `arr.filter()` is called, it internally creates the new array of results using exactly `arr.constructor`, not basic `Array`. That's actually very cool, because we can keep using `PowerArray` methods further on the result. Even more, we can customize that behavior. We can add a special static getter `Symbol.species` to the class. If exists, it should return the constructor that JavaScript will use internally to create new entities in `map`, `filter` and so on. -If we'd like built-in methods like `map`, `filter` will return regular arrays, we can return `Array` in `Symbol.species`, like here: +If we'd like built-in methods like `map` or `filter` to return regular arrays, we can return `Array` in `Symbol.species`, like here: ```js run class PowerArray extends Array { @@ -64,27 +64,26 @@ alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function As you can see, now `.filter` returns `Array`. So the extended functionality is not passed any further. +```smart header="Other collections work similarly" +Other collections, such as `Map` and `Set`, work alike. They also use `Symbol.species`. +``` + ## No static inheritance in built-ins Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray` etc. As we already know, native classes extend each other. For instance, `Array` extends `Object`. -Normally, when one class extends another, both static and non-static methods are inherited. - -So, if `Rabbit extends Animal`, then: +Normally, when one class extends another, both static and non-static methods are inherited. That was thoroughly explained in the chapter [](info:static-properties-methods#statics-and-inheritance). -1. `Rabbit.methods` are callable for `Animal.methods`, because `Rabbit.[[Prototype]] = Animal`. -2. `new Rabbit().methods` are also available, because `Rabbit.prototype.[[Prototype]] = Animal.prototype`. +But built-in classes are an exception. They don't inherit statics from each other. -That's thoroughly explained in the chapter [](info:static-properties-methods#statics-and-inheritance). - -But built-in classes are an exception. They don't inherit statics `(1)` from each other. - -For example, both `Array` and `Date` inherit from `Object`, so their instances have methods from `Object.prototype`. But `Array.[[Prototype]]` does not point to `Object`. So there's `Object.keys()`, but not `Array.keys()` and `Date.keys()`. +For example, both `Array` and `Date` inherit from `Object`, so their instances have methods from `Object.prototype`. But `Array.[[Prototype]]` does not reference `Object`, so there's no `Array.keys()` and `Date.keys()` static methods. Here's the picture structure for `Date` and `Object`: -![](object-date-inheritance.png) +![](object-date-inheritance.svg) + +As you can see, there's no link between `Date` and `Object`. They are independent, only `Date.prototype` inherits from `Object.prototype`. -Note, there's no link between `Date` and `Object`. Both `Object` and `Date` exist independently. `Date.prototype` inherits from `Object.prototype`, but that's all. +That's an important difference of inheritance between built-in objects compared to what we get with `extends`. diff --git a/1-js/09-classes/05-extend-natives/object-date-inheritance.png b/1-js/09-classes/05-extend-natives/object-date-inheritance.png deleted file mode 100644 index 73020a49e..000000000 Binary files a/1-js/09-classes/05-extend-natives/object-date-inheritance.png and /dev/null differ diff --git a/1-js/09-classes/05-extend-natives/object-date-inheritance.svg b/1-js/09-classes/05-extend-natives/object-date-inheritance.svg new file mode 100644 index 000000000..a0165bccb --- /dev/null +++ b/1-js/09-classes/05-extend-natives/object-date-inheritance.svg @@ -0,0 +1 @@ +constructor: Object toString: function hasOwnProperty: function ...Object.prototypeconstructor: Date toString: function getDate: function ...Date.prototypeObjectDatenew Date()[[Prototype]][[Prototype]]prototypeprototypedefineProperty keys ...now parse ...1 Jan 2019 \ No newline at end of file diff --git a/1-js/09-classes/05-extend-natives/object-date-inheritance@2x.png b/1-js/09-classes/05-extend-natives/object-date-inheritance@2x.png deleted file mode 100644 index 6520f9e26..000000000 Binary files a/1-js/09-classes/05-extend-natives/object-date-inheritance@2x.png and /dev/null differ diff --git a/1-js/09-classes/06-instanceof/article.md b/1-js/09-classes/06-instanceof/article.md index dca6ac627..0b02c99be 100644 --- a/1-js/09-classes/06-instanceof/article.md +++ b/1-js/09-classes/06-instanceof/article.md @@ -11,7 +11,7 @@ The syntax is: obj instanceof Class ``` -It returns `true` if `obj` belongs to the `Class` (or a class inheriting from it). +It returns `true` if `obj` belongs to the `Class` or a class inheriting from it. For instance: @@ -46,15 +46,17 @@ alert( arr instanceof Object ); // true Please note that `arr` also belongs to the `Object` class. That's because `Array` prototypally inherits from `Object`. -The `instanceof` operator examines the prototype chain for the check, but we can set a custom logic the static method `Symbol.hasInstance`. +Normally, `instanceof` operator examines the prototype chain for the check. We can also set a custom logic in the static method `Symbol.hasInstance`. The algorithm of `obj instanceof Class` works roughly as follows: -1. If there's a static method `Symbol.hasInstance`, then just call it: `Class[Symbol.hasInstance](obj)`. It should return either `true` or `false`. We're done. - For example: +1. If there's a static method `Symbol.hasInstance`, then just call it: `Class[Symbol.hasInstance](obj)`. It should return either `true` or `false`, and we're done. That's how we can customize the behavior of `instanceof`. + + For example: ```js run - // setup instanceOf check that assumes that anything that canEat is an animal + // setup instanceOf check that assumes that + // anything with canEat property is an animal class Animal { static [Symbol.hasInstance](obj) { if (obj.canEat) return true; @@ -66,19 +68,21 @@ The algorithm of `obj instanceof Class` works roughly as follows: alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called ``` -2. Most classes do not have `Symbol.hasInstance`. In that case, the standard logic is used: `obj instanceOf Classs` checks whether `Class.prototype` equals to one of prototypes in the `obj` prototype chain. +2. Most classes do not have `Symbol.hasInstance`. In that case, the standard logic is used: `obj instanceOf Class` checks whether `Class.prototype` equals to one of prototypes in the `obj` prototype chain. - In other words, compare: + In other words, compare one after another: ```js - obj.__proto__ === Class.prototype - obj.__proto__.__proto__ === Class.prototype - obj.__proto__.__proto__.__proto__ === Class.prototype + obj.__proto__ === Class.prototype? + obj.__proto__.__proto__ === Class.prototype? + obj.__proto__.__proto__.__proto__ === Class.prototype? ... + // if any answer is true, return true + // otherwise, if we reached the end of the chain, return false ``` - In the example above `Rabbit.prototype === rabbit.__proto__`, so that gives the answer immediately. + In the example above `rabbit.__proto__ === Rabbit.prototype`, so that gives the answer immediately. - In the case of an inheritance, `rabbit` is an instance of the parent class as well: + In the case of an inheritance, the match will be at the second step: ```js run class Animal {} @@ -88,19 +92,22 @@ The algorithm of `obj instanceof Class` works roughly as follows: *!* alert(rabbit instanceof Animal); // true */!* + // rabbit.__proto__ === Rabbit.prototype + *!* // rabbit.__proto__.__proto__ === Animal.prototype (match!) + */!* ``` Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`: -![](instanceof.png) +![](instanceof.svg) By the way, there's also a method [objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf), that returns `true` if `objA` is somewhere in the chain of prototypes for `objB`. So the test of `obj instanceof Class` can be rephrased as `Class.prototype.isPrototypeOf(obj)`. That's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters. -That can lead to interesting consequences when `prototype` is changed. +That can lead to interesting consequences when `prototype` property is changed after the object is created. Like here: @@ -117,8 +124,6 @@ alert( rabbit instanceof Rabbit ); // false */!* ``` -That's one of the reasons to avoid changing `prototype`. Just to keep safe. - ## Bonus: Object.prototype.toString for the type We already know that plain objects are converted to string as `[object Object]`: @@ -152,7 +157,7 @@ let objectToString = Object.prototype.toString; // what type is this? let arr = []; -alert( objectToString.call(arr) ); // [object Array] +alert( objectToString.call(arr) ); // [object *!*Array*/!*] ``` Here we used [call](mdn:js/function/call) as described in the chapter [](info:call-apply-decorators) to execute the function `objectToString` in the context `this=arr`. @@ -196,11 +201,11 @@ As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped At the end we have "typeof on steroids" that not only works for primitive data types, but also for built-in objects and even can be customized. -It can be used instead of `instanceof` for built-in objects when we want to get the type as a string rather than just to check. +We can use `{}.toString.call` instead of `instanceof` for built-in objects when we want to get the type as a string rather than just to check. ## Summary -Let's recap the type-checking methods that we know: +Let's summarize the type-checking methods that we know: | | works for | returns | |---------------|-------------|---------------| diff --git a/1-js/09-classes/06-instanceof/instanceof.png b/1-js/09-classes/06-instanceof/instanceof.png deleted file mode 100644 index ad0fc77ab..000000000 Binary files a/1-js/09-classes/06-instanceof/instanceof.png and /dev/null differ diff --git a/1-js/09-classes/06-instanceof/instanceof.svg b/1-js/09-classes/06-instanceof/instanceof.svg new file mode 100644 index 000000000..920be68b7 --- /dev/null +++ b/1-js/09-classes/06-instanceof/instanceof.svg @@ -0,0 +1 @@ +Animal.prototypeObject.prototypeRabbit.prototype[[Prototype]]rabbit[[Prototype]][[Prototype]]null[[Prototype]]= Animal.prototype? \ No newline at end of file diff --git a/1-js/09-classes/06-instanceof/instanceof@2x.png b/1-js/09-classes/06-instanceof/instanceof@2x.png deleted file mode 100644 index c25b166b3..000000000 Binary files a/1-js/09-classes/06-instanceof/instanceof@2x.png and /dev/null differ diff --git a/1-js/09-classes/07-mixins/article.md b/1-js/09-classes/07-mixins/article.md index 30651688e..d5f1ab832 100644 --- a/1-js/09-classes/07-mixins/article.md +++ b/1-js/09-classes/07-mixins/article.md @@ -2,19 +2,19 @@ In JavaScript we can only inherit from a single object. There can be only one `[[Prototype]]` for an object. And a class may extend only one other class. -But sometimes that feels limiting. For instance, I have a class `StreetSweeper` and a class `Bicycle`, and want to make a `StreetSweepingBicycle`. +But sometimes that feels limiting. For instance, we have a class `StreetSweeper` and a class `Bicycle`, and want to make their mix: a `StreetSweepingBicycle`. -Or, talking about programming, we have a class `User` and a class `EventEmitter` that implements event generation, and we'd like to add the functionality of `EventEmitter` to `User`, so that our users can emit events. +Or we have a class `User` and a class `EventEmitter` that implements event generation, and we'd like to add the functionality of `EventEmitter` to `User`, so that our users can emit events. There's a concept that can help here, called "mixins". -As defined in Wikipedia, a [mixin](https://en.wikipedia.org/wiki/Mixin) is a class that contains methods for use by other classes without having to be the parent class of those other classes. +As defined in Wikipedia, a [mixin](https://en.wikipedia.org/wiki/Mixin) is a class containing methods that can be used by other classes without a need to inherit from it. In other words, a *mixin* provides methods that implement a certain behavior, but we do not use it alone, we use it to add the behavior to other classes. ## A mixin example -The simplest way to make a mixin in JavaScript is to make an object with useful methods, so that we can easily merge them into a prototype of any class. +The simplest way to implement a mixin in JavaScript is to make an object with useful methods, so that we can easily merge them into a prototype of any class. For instance here the mixin `sayHiMixin` is used to add some "speech" for `User`: @@ -75,10 +75,10 @@ let sayHiMixin = { *!* // call parent method */!* - super.say(`Hello ${this.name}`); + super.say(`Hello ${this.name}`); // (*) }, sayBye() { - super.say(`Bye ${this.name}`); + super.say(`Bye ${this.name}`); // (*) } }; @@ -95,11 +95,13 @@ Object.assign(User.prototype, sayHiMixin); new User("Dude").sayHi(); // Hello Dude! ``` -Please note that the call to the parent method `super.say()` from `sayHiMixin` looks for the method in the prototype of that mixin, not the class. +Please note that the call to the parent method `super.say()` from `sayHiMixin` (at lines labelled with `(*)`) looks for the method in the prototype of that mixin, not the class. -![](mixin-inheritance.png) +Here's the diagram (see the right part): -That's because methods `sayHi` and `sayBye` were initially created in `sayHiMixin`. So their `[[HomeObject]]` internal property references `sayHiMixin`, as shown on the picture above. +![](mixin-inheritance.svg) + +That's because methods `sayHi` and `sayBye` were initially created in `sayHiMixin`. So even though they got copied, their `[[HomeObject]]` internal property references `sayHiMixin`, as shown on the picture above. As `super` looks for parent methods in `[[HomeObject]].[[Prototype]]`, that means it searches `sayHiMixin.[[Prototype]]`, not `User.[[Prototype]]`. @@ -107,7 +109,7 @@ As `super` looks for parent methods in `[[HomeObject]].[[Prototype]]`, that mean Now let's make a mixin for real life. -The important feature of many browser objects (not only) can generate events. Events is a great way to "broadcast information" to anyone who wants it. So let's make a mixin that allows to easily add event-related functions to any class/object. +An important feature of many browser objects (for instance) is that they can generate events. Events is a great way to "broadcast information" to anyone who wants it. So let's make a mixin that allows to easily add event-related functions to any class/object. - The mixin will provide a method `.trigger(name, [...data])` to "generate an event" when something important happens to it. The `name` argument is a name of the event, optionally followed by additional arguments with event data. - Also the method `.on(name, handler)` that adds `handler` function as the listener to events with the given name. It will be called when an event with the given `name` triggers, and get the arguments from `.trigger` call. @@ -199,8 +201,8 @@ And `eventMixin` mixin makes it easy to add such behavior to as many classes as *Mixin* -- is a generic object-oriented programming term: a class that contains methods for other classes. -Some other languages like e.g. Python allow to create mixins using multiple inheritance. JavaScript does not support multiple inheritance, but mixins can be implemented by copying methods into prototype. +Some other languages like allow multiple inheritance. JavaScript does not support multiple inheritance, but mixins can be implemented by copying methods into prototype. We can use mixins as a way to augment a class by multiple behaviors, like event-handling as we have seen above. -Mixins may become a point of conflict if they occasionally overwrite existing class methods. So generally one should think well about the naming methods of a mixin, to minimize the probability of that. +Mixins may become a point of conflict if they accidentally overwrite existing class methods. So generally one should think well about the naming methods of a mixin, to minimize the probability of that. diff --git a/1-js/09-classes/07-mixins/mixin-inheritance.png b/1-js/09-classes/07-mixins/mixin-inheritance.png deleted file mode 100644 index 6142ce7fc..000000000 Binary files a/1-js/09-classes/07-mixins/mixin-inheritance.png and /dev/null differ diff --git a/1-js/09-classes/07-mixins/mixin-inheritance.svg b/1-js/09-classes/07-mixins/mixin-inheritance.svg new file mode 100644 index 000000000..2e7ba8b39 --- /dev/null +++ b/1-js/09-classes/07-mixins/mixin-inheritance.svg @@ -0,0 +1 @@ +sayHi: function sayBye: functionsayHiMixinsay: functionsayMixin[[Prototype]]constructor: User sayHi: function sayBye: functionUser.prototype[[Prototype]]name: ...user[[HomeObject] \ No newline at end of file diff --git a/1-js/09-classes/07-mixins/mixin-inheritance@2x.png b/1-js/09-classes/07-mixins/mixin-inheritance@2x.png deleted file mode 100644 index ccbd74300..000000000 Binary files a/1-js/09-classes/07-mixins/mixin-inheritance@2x.png and /dev/null differ diff --git a/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/solution.md b/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/solution.md index 05ba72e00..303431d6d 100644 --- a/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/solution.md +++ b/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/solution.md @@ -44,4 +44,4 @@ function f() { f(); // cleanup! ``` -It's `finally` that guarantees the cleanup here. If we just put the code at the end of `f`, it wouldn't run. +It's `finally` that guarantees the cleanup here. If we just put the code at the end of `f`, it wouldn't run in these situations. diff --git a/1-js/10-error-handling/1-try-catch/article.md b/1-js/10-error-handling/1-try-catch/article.md index 4a1adba0c..fa8ba5e93 100644 --- a/1-js/10-error-handling/1-try-catch/article.md +++ b/1-js/10-error-handling/1-try-catch/article.md @@ -25,14 +25,14 @@ try { It works like this: 1. First, the code in `try {...}` is executed. -2. If there were no errors, then `catch(err)` is ignored: the execution reaches the end of `try` and then jumps over `catch`. +2. If there were no errors, then `catch(err)` is ignored: the execution reaches the end of `try` and goes on skipping `catch`. 3. If an error occurs, then `try` execution is stopped, and the control flows to the beginning of `catch(err)`. The `err` variable (can use any name for it) contains an error object with details about what's happened. -![](try-catch-flow.png) +![](try-catch-flow.svg) So, an error inside the `try {…}` block does not kill the script: we have a chance to handle it in `catch`. -Let's see more examples. +Let's see examples. - An errorless example: shows `alert` `(1)` and `(2)`: @@ -50,8 +50,6 @@ Let's see more examples. alert('Catch is ignored, because there are no errors'); // (3) } - - alert("...Then the execution continues"); ``` - An example with an error: shows `(1)` and `(3)`: @@ -71,8 +69,6 @@ Let's see more examples. alert(`Error has occurred!`); // *!*(3) <--*/!* } - - alert("...Then the execution continues"); ``` @@ -134,10 +130,10 @@ try { } ``` -For all built-in errors, the error object inside `catch` block has two main properties: +For all built-in errors, the error object has two main properties: `name` -: Error name. For an undefined variable that's `"ReferenceError"`. +: Error name. For instance, for an undefined variable that's `"ReferenceError"`. `message` : Textual message about error details. @@ -157,7 +153,7 @@ try { } catch(err) { alert(err.name); // ReferenceError alert(err.message); // lalala is not defined - alert(err.stack); // ReferenceError: lalala is not defined at ... + alert(err.stack); // ReferenceError: lalala is not defined at (...call stack) // Can also show an error as a whole // The error is converted to string as "name: message" @@ -174,8 +170,8 @@ If we don't need error details, `catch` may omit it: ```js try { // ... -} catch { - // error object omitted +} catch { // <-- without (err) + // ... } ``` @@ -187,7 +183,7 @@ As we already know, JavaScript supports the [JSON.parse(str)](mdn:js/JSON/parse) Usually it's used to decode data received over the network, from the server or another source. -We receive it and call `JSON.parse`, like this: +We receive it and call `JSON.parse` like this: ```js run let json = '{"name":"John", "age": 30}'; // data from the server @@ -302,13 +298,13 @@ try { *!* alert(e.name); // SyntaxError */!* - alert(e.message); // Unexpected token o in JSON at position 0 + alert(e.message); // Unexpected token o in JSON at position 2 } ``` As we can see, that's a `SyntaxError`. -And in our case, the absence of `name` could be treated as a syntax error also, assuming that users must have a `name`. +And in our case, the absence of `name` is an error, as users must have a `name`. So let's throw it: @@ -534,7 +530,7 @@ In other words, the function may finish with `return` or `throw`, that doesn't m ```smart header="Variables are local inside `try..catch..finally`" Please note that `result` and `diff` variables in the code above are declared *before* `try..catch`. -Otherwise, if `let` were made inside the `{...}` block, it would only be visible inside of it. +Otherwise, if we declared `let` in `try` block, it would only be visible inside of it. ``` ````smart header="`finally` and `return`" @@ -565,7 +561,7 @@ alert( func() ); // first works alert from finally, and then this one ````smart header="`try..finally`" -The `try..finally` construct, without `catch` clause, is also useful. We apply it when we don't want to handle errors right here, but want to be sure that processes that we started are finalized. +The `try..finally` construct, without `catch` clause, is also useful. We apply it when we don't want to handle errors here (let them fall through), but want to be sure that processes that we started are finalized. ```js function func() { @@ -577,7 +573,7 @@ function func() { } } ``` -In the code above, an error inside `try` always falls out, because there's no `catch`. But `finally` works before the execution flow jumps outside. +In the code above, an error inside `try` always falls out, because there's no `catch`. But `finally` works before the execution flow leaves the function. ```` ## Global catch @@ -590,7 +586,7 @@ Let's imagine we've got a fatal error outside of `try..catch`, and the script di Is there a way to react on such occurrences? We may want to log the error, show something to the user (normally they don't see error messages) etc. -There is none in the specification, but environments usually provide it, because it's really useful. For instance, Node.js has [process.on('uncaughtException')](https://nodejs.org/api/process.html#process_event_uncaughtexception) for that. And in the browser we can assign a function to special [window.onerror](mdn:api/GlobalEventHandlers/onerror) property. It will run in case of an uncaught error. +There is none in the specification, but environments usually provide it, because it's really useful. For instance, Node.js has [`process.on("uncaughtException")`](https://nodejs.org/api/process.html#process_event_uncaughtexception) for that. And in the browser we can assign a function to special [window.onerror](mdn:api/GlobalEventHandlers/onerror) property, that will run in case of an uncaught error. The syntax: @@ -637,7 +633,7 @@ There are also web-services that provide error-logging for such cases, like BeginNo ErrorsAn error occured in the codeIgnore catch blockIgnore the rest of tryExecute catch blocktry { }// code... \ No newline at end of file diff --git a/1-js/10-error-handling/1-try-catch/try-catch-flow@2x.png b/1-js/10-error-handling/1-try-catch/try-catch-flow@2x.png deleted file mode 100644 index f85eb6321..000000000 Binary files a/1-js/10-error-handling/1-try-catch/try-catch-flow@2x.png and /dev/null differ diff --git a/1-js/10-error-handling/2-custom-errors/article.md b/1-js/10-error-handling/2-custom-errors/article.md index 70ff1dec1..2414ce7ef 100644 --- a/1-js/10-error-handling/2-custom-errors/article.md +++ b/1-js/10-error-handling/2-custom-errors/article.md @@ -17,17 +17,13 @@ Here's an example of how a valid `json` may look: let json = `{ "name": "John", "age": 30 }`; ``` -Internally, we'll use `JSON.parse`. If it receives malformed `json`, then it throws `SyntaxError`. - -But even if `json` is syntactically correct, that doesn't mean that it's a valid user, right? It may miss the necessary data. For instance, it may not have `name` and `age` properties that are essential for our users. +Internally, we'll use `JSON.parse`. If it receives malformed `json`, then it throws `SyntaxError`. But even if `json` is syntactically correct, that doesn't mean that it's a valid user, right? It may miss the necessary data. For instance, it may not have `name` and `age` properties that are essential for our users. Our function `readUser(json)` will not only read JSON, but check ("validate") the data. If there are no required fields, or the format is wrong, then that's an error. And that's not a `SyntaxError`, because the data is syntactically correct, but another kind of error. We'll call it `ValidationError` and create a class for it. An error of that kind should also carry the information about the offending field. Our `ValidationError` class should inherit from the built-in `Error` class. -That class is built-in, but we should have its approximate code before our eyes, to understand what we're extending. - -So here you are: +That class is built-in, here's it approximate code, for us to understand what we're extending: ```js // The "pseudocode" for the built-in Error class defined by JavaScript itself @@ -35,12 +31,12 @@ class Error { constructor(message) { this.message = message; this.name = "Error"; // (different names for different built-in error classes) - this.stack = ; // non-standard, but most environments support it + this.stack = ; // non-standard, but most environments support it } } ``` -Now let's go on and inherit `ValidationError` from it: +Now let's inherit `ValidationError` from it and try it in action: ```js run untrusted *!* @@ -65,10 +61,9 @@ try { } ``` -Please take a look at the constructor: +Please note: in the line `(1)` we call the parent constructor. JavaScript requires us to call `super` in the child constructor, so that's obligatory. The parent constructor sets the `message` property. -1. In the line `(1)` we call the parent constructor. JavaScript requires us to call `super` in the child constructor, so that's obligatory. The parent constructor sets the `message` property. -2. The parent constructor also sets the `name` property to `"Error"`, so in the line `(2)` we reset it to the right value. +The parent constructor also sets the `name` property to `"Error"`, so in the line `(2)` we reset it to the right value. Let's try to use it in `readUser(json)`: @@ -185,7 +180,7 @@ try { The new class `PropertyRequiredError` is easy to use: we only need to pass the property name: `new PropertyRequiredError(property)`. The human-readable `message` is generated by the constructor. -Please note that `this.name` in `PropertyRequiredError` constructor is again assigned manually. That may become a bit tedious -- to assign `this.name = ` in every custom error class. But there's a way out. We can make our own "basic error" class that removes this burden from our shoulders by using `this.constructor.name` for `this.name` in its constructor. And then inherit all ours custom errors from it. +Please note that `this.name` in `PropertyRequiredError` constructor is again assigned manually. That may become a bit tedious -- to assign `this.name = ` in every custom error class. We can avoid it by making our own "basic error" class that assigns `this.name = this.constructor.name`. And then inherit all ours custom errors from it. Let's call it `MyError`. @@ -218,9 +213,9 @@ Now custom errors are much shorter, especially `ValidationError`, as we got rid ## Wrapping exceptions -The purpose of the function `readUser` in the code above is "to read the user data", right? There may occur different kinds of errors in the process. Right now we have `SyntaxError` and `ValidationError`, but in the future `readUser` function may grow and probably generate other kinds of errors. +The purpose of the function `readUser` in the code above is "to read the user data". There may occur different kinds of errors in the process. Right now we have `SyntaxError` and `ValidationError`, but in the future `readUser` function may grow and probably generate other kinds of errors. -The code which calls `readUser` should handle these errors. Right now it uses multiple `if` in the `catch` block to check for different error types and rethrow the unknown ones. But if `readUser` function generates several kinds of errors -- then we should ask ourselves: do we really want to check for all error types one-by-one in every code that calls `readUser`? +The code which calls `readUser` should handle these errors. Right now it uses multiple `if` in the `catch` block, that check the class and handle known errors and rethrow the unknown ones. But if `readUser` function generates several kinds of errors -- then we should ask ourselves: do we really want to check for all error types one-by-one in every code that calls `readUser`? Often the answer is "No": the outer code wants to be "one level above all that". It wants to have some kind of "data reading error". Why exactly it happened -- is often irrelevant (the error message describes it). Or, even better if there is a way to get error details, but only if we need to. diff --git a/1-js/11-async/01-callbacks/article.md b/1-js/11-async/01-callbacks/article.md index ee0bb3caa..c2f67c6cc 100644 --- a/1-js/11-async/01-callbacks/article.md +++ b/1-js/11-async/01-callbacks/article.md @@ -25,15 +25,16 @@ loadScript('/my/script.js'); The function is called "asynchronously," because the action (script loading) finishes not now, but later. -The call initiates the script loading, then the execution continues. While the script is loading, the code below may finish executing, and if the loading takes time, other scripts may run meanwhile too. +If there's a code below `loadScript(…)`, it doesn't wait until the loading finishes. ```js loadScript('/my/script.js'); -// the code below loadScript doesn't wait for the script loading to finish +// the code below loadScript +// doesn't wait for the script loading to finish // ... ``` -Now let's say we want to use the new script when it loads. It probably declares new functions, so we'd like to run them. +We'd like to use the new script as soon as it loads. It declares new functions, and we want to run them. But if we do that immediately after the `loadScript(…)` call, that wouldn't work: @@ -45,7 +46,7 @@ newFunction(); // no such function! */!* ``` -Naturally, the browser probably didn't have time to load the script. So the immediate call to the new function fails. As of now, the `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when it happens, to use new functions and variables from that script. +Naturally, the browser probably didn't have time to load the script. As of now, the `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when it happens, to use new functions and variables from that script. Let's add a `callback` function as a second argument to `loadScript` that should execute when the script loads: @@ -222,7 +223,31 @@ As calls become more nested, the code becomes deeper and increasingly more diffi That's sometimes called "callback hell" or "pyramid of doom." -![](callback-hell.png) + + +![](callback-hell.svg) The "pyramid" of nested calls grows to the right with every asynchronous action. Soon it spirals out of control. diff --git a/1-js/11-async/01-callbacks/callback-hell.png b/1-js/11-async/01-callbacks/callback-hell.png deleted file mode 100644 index 567ec284e..000000000 Binary files a/1-js/11-async/01-callbacks/callback-hell.png and /dev/null differ diff --git a/1-js/11-async/01-callbacks/callback-hell.svg b/1-js/11-async/01-callbacks/callback-hell.svg new file mode 100644 index 000000000..907f62c2a --- /dev/null +++ b/1-js/11-async/01-callbacks/callback-hell.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/1-js/11-async/01-callbacks/callback-hell@2x.png b/1-js/11-async/01-callbacks/callback-hell@2x.png deleted file mode 100644 index 4d6b0ad70..000000000 Binary files a/1-js/11-async/01-callbacks/callback-hell@2x.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/article.md b/1-js/11-async/02-promise-basics/article.md index dd9e239c4..791ddba3e 100644 --- a/1-js/11-async/02-promise-basics/article.md +++ b/1-js/11-async/02-promise-basics/article.md @@ -2,7 +2,7 @@ Imagine that you're a top singer, and fans ask day and night for your upcoming single. -To get some relief, you promise to send it to them when it's published. You give your fans a list to which they can subscribe for updates. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, if plans to publish the song are cancelled, they will still be notified. +To get some relief, you promise to send it to them when it's published. You give your fans a list. They can fill in their email addresses, so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, fire in the studio, so that you can't publish the song, they will still be notified. Everyone is happy, because the people don't crowd you anymore, and fans, because they won't miss the single. @@ -22,27 +22,29 @@ let promise = new Promise(function(resolve, reject) { }); ``` -The function passed to `new Promise` is called the *executor*. When the promise is created, this executor function runs automatically. It contains the producing code, that should eventually produce a result. In terms of the analogy above: the executor is the "singer". +The function passed to `new Promise` is called the *executor*. When the promise is created, it runs automatically. It contains the producing code, that should eventually produce a result. In terms of the analogy above: the executor is the "singer". -The resulting `promise` object has internal properties: +Its arguments `resolve` and `reject` are callbacks provided by JavaScript itself. Our code is only inside executor. -- `state` — initially "pending", then changes to either "fulfilled" or "rejected", -- `result` — an arbitrary value, initially `undefined`. +When the executor obtains the result, be it soon or late - doesn't matter, it should call one of these callbacks: -When the executor finishes the job, it should call one of the functions that it gets as arguments: +- `resolve(value)` — if the job finished successfully, with result `value`. +- `reject(error)` — if an error occurred, `error` is the error object. -- `resolve(value)` — to indicate that the job finished successfully: - - sets `state` to `"fulfilled"`, - - sets `result` to `value`. -- `reject(error)` — to indicate that an error occurred: - - sets `state` to `"rejected"`, - - sets `result` to `error`. +So to summarize: the executor runs automatically, it should do a job and then call either `resolve` or `reject`. -![](promise-resolve-reject.png) +The `promise` object returned by `new Promise` constructor has internal properties: -Later we'll see how these changes become known to "fans". +- `state` — initially `"pending"`, then changes to either `"fulfilled"` when `resolve` is called or `"rejected"` when `reject` is called. +- `result` — initially `undefined`, then changes to `value` when `resolve(value)` called or `error` when `reject(error)` is called. -Here's an example of a Promise constructor and a simple executor function with its "producing code" (the `setTimeout`): +So the executor moves `promise` to one of these states: + +![](promise-resolve-reject.svg) + +Later we'll see how "fans" can subscribe to these changes. + +Here's an example of a Promise constructor and a simple executor function with delayed "producing code" (via `setTimeout`): ```js run let promise = new Promise(function(resolve, reject) { @@ -60,7 +62,7 @@ We can see two things by running the code above: After one second of "processing" the executor calls `resolve("done")` to produce the result: -![](promise-resolve-1.png) +![](promise-resolve-1.svg) That was an example of a successful job completion, a "fulfilled promise". @@ -73,7 +75,7 @@ let promise = new Promise(function(resolve, reject) { }); ``` -![](promise-reject-1.png) +![](promise-reject-1.svg) To summarize, the executor should do a job (something that takes time usually) and then call `resolve` or `reject` to change the state of the corresponding Promise object. @@ -86,7 +88,9 @@ All further calls of `resolve` and `reject` are ignored: ```js let promise = new Promise(function(resolve, reject) { +*!* resolve("done"); +*/!* reject(new Error("…")); // ignored setTimeout(() => resolve("…")); // ignored @@ -99,7 +103,7 @@ Also, `resolve`/`reject` expect only one argument (or none) and will ignore addi ```` ```smart header="Reject with `Error` objects" -In case something goes wrong, we can call `reject` with any type of argument (just like `resolve`). But it is recommended to use `Error` objects (or objects that inherit from `Error`). The reasoning for that will soon become apparent. +In case something goes wrong, we must call `reject`. That can be done with any type of argument (just like `resolve`). But it is recommended to use `Error` objects (or objects that inherit from `Error`). The reasoning for that will soon become apparent. ``` ````smart header="Immediately calling `resolve`/`reject`" @@ -112,13 +116,13 @@ let promise = new Promise(function(resolve, reject) { }); ``` -For instance, this might happen when we start to do a job but then see that everything has already been completed and cached. +For instance, this might happen when we start to do a job but then see that everything has already been completed and cached. That's fine. We immediately have a resolved promise. ```` ```smart header="The `state` and `result` are internal" -The properties `state` and `result` of the Promise object are internal. We can't directly access them from our "consuming code". We can use the methods `.then`/`.catch`/`.finally` for that. They are described below. +The properties `state` and `result` of the Promise object are internal. We can't directly access them. We can use the methods `.then`/`.catch`/`.finally` for that. They are described below. ``` ## Consumers: then, catch, finally @@ -138,15 +142,9 @@ promise.then( ); ``` -The first argument of `.then` is a function that: - -1. runs when the promise is resolved, and -2. receives the result. +The first argument of `.then` is a function that runs when the promise is resolved, and receives the result. -The second argument of `.then` is a function that: - -1. runs when the promise is rejected, and -2. receives the error. +The second argument of `.then` is a function that runs when the promise is rejected, and receives the error. For instance, here's a reaction to a successfully resolved promise: @@ -216,7 +214,7 @@ The call `.catch(f)` is a complete analog of `.then(null, f)`, it's just a short Just like there's a `finally` clause in a regular `try {...} catch {...}`, there's `finally` in promises. -The call `.finally(f)` is similar to `.then(f, f)` in the sense that it always runs when the promise is settled: be it resolve or reject. +The call `.finally(f)` is similar to `.then(f, f)` in the sense that `f` always runs when the promise is settled: be it resolve or reject. `finally` is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed anymore, no matter what the outcome is. @@ -264,7 +262,7 @@ It's not exactly an alias of `then(f,f)` though. There are several important dif 3. Last, but not least, `.finally(f)` is a more convenient syntax than `.then(f, f)`: no need to duplicate the function `f`. ````smart header="On settled promises handlers runs immediately" -If a promise is pending, `.then/catch/finally` handlers wait for the result. Otherwise, if a promise has already settled, they execute immediately: +If a promise is pending, `.then/catch/finally` handlers wait for it. Otherwise, if a promise has already settled, they execute immediately: ```js run // an immediately resolved promise @@ -272,8 +270,6 @@ let promise = new Promise(resolve => resolve("done!")); promise.then(alert); // done! (shows up right now) ``` - -The good thing is: a `.then` handler is guaranteed to run whether the promise takes time or settles it immediately. ```` Next, let's see more practical examples of how promises can help us to write asynchronous code. @@ -324,7 +320,7 @@ promise.then( error => alert(`Error: ${error.message}`) ); -promise.then(script => alert('One more handler to do something else!')); +promise.then(script => alert('Another handler...')); ``` We can immediately see a few benefits over the callback-based pattern: @@ -335,4 +331,4 @@ We can immediately see a few benefits over the callback-based pattern: | Promises allow us to do things in the natural order. First, we run `loadScript(script)`, and `.then` we write what to do with the result. | We must have a `callback` function at our disposal when calling `loadScript(script, callback)`. In other words, we must know what to do with the result *before* `loadScript` is called. | | We can call `.then` on a Promise as many times as we want. Each time, we're adding a new "fan", a new subscribing function, to the "subscription list". More about this in the next chapter: [](info:promise-chaining). | There can be only one callback. | -So Promises give us better code flow and flexibility. But there's more. We'll see that in the next chapters. +So promises give us better code flow and flexibility. But there's more. We'll see that in the next chapters. diff --git a/1-js/11-async/02-promise-basics/promise-init.png b/1-js/11-async/02-promise-basics/promise-init.png deleted file mode 100644 index c54ce05f1..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-init.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-init@2x.png b/1-js/11-async/02-promise-basics/promise-init@2x.png deleted file mode 100644 index 82f0d7138..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-init@2x.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-reject-1.png b/1-js/11-async/02-promise-basics/promise-reject-1.png deleted file mode 100644 index 3ae74879c..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-reject-1.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-reject-1.svg b/1-js/11-async/02-promise-basics/promise-reject-1.svg new file mode 100644 index 000000000..5a94d8052 --- /dev/null +++ b/1-js/11-async/02-promise-basics/promise-reject-1.svg @@ -0,0 +1 @@ +new Promise(executor)state: "pending" result: undefinedreject(error)state: "rejected" result: error \ No newline at end of file diff --git a/1-js/11-async/02-promise-basics/promise-reject-1@2x.png b/1-js/11-async/02-promise-basics/promise-reject-1@2x.png deleted file mode 100644 index 9eff3793c..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-reject-1@2x.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-resolve-1.png b/1-js/11-async/02-promise-basics/promise-resolve-1.png deleted file mode 100644 index b4bb51826..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-resolve-1.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-resolve-1.svg b/1-js/11-async/02-promise-basics/promise-resolve-1.svg new file mode 100644 index 000000000..f70eec8cc --- /dev/null +++ b/1-js/11-async/02-promise-basics/promise-resolve-1.svg @@ -0,0 +1 @@ +new Promise(executor)state: "pending" result: undefinedresolve("done")state: "fulfilled" result: "done" \ No newline at end of file diff --git a/1-js/11-async/02-promise-basics/promise-resolve-1@2x.png b/1-js/11-async/02-promise-basics/promise-resolve-1@2x.png deleted file mode 100644 index ecb4af35d..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-resolve-1@2x.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-resolve-reject.png b/1-js/11-async/02-promise-basics/promise-resolve-reject.png deleted file mode 100644 index 6f0294f01..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-resolve-reject.png and /dev/null differ diff --git a/1-js/11-async/02-promise-basics/promise-resolve-reject.svg b/1-js/11-async/02-promise-basics/promise-resolve-reject.svg new file mode 100644 index 000000000..657da3ff6 --- /dev/null +++ b/1-js/11-async/02-promise-basics/promise-resolve-reject.svg @@ -0,0 +1 @@ +new Promise(executor)state: "pending" result: undefinedresolve(value)reject(error)state: "fulfilled" result: valuestate: "rejected" result: error \ No newline at end of file diff --git a/1-js/11-async/02-promise-basics/promise-resolve-reject@2x.png b/1-js/11-async/02-promise-basics/promise-resolve-reject@2x.png deleted file mode 100644 index b59301ff7..000000000 Binary files a/1-js/11-async/02-promise-basics/promise-resolve-reject@2x.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/article.md b/1-js/11-async/03-promise-chaining/article.md index 858f12d8f..e35c619ef 100644 --- a/1-js/11-async/03-promise-chaining/article.md +++ b/1-js/11-async/03-promise-chaining/article.md @@ -42,30 +42,12 @@ Here the flow is: As the result is passed along the chain of handlers, we can see a sequence of `alert` calls: `1` -> `2` -> `4`. -![](promise-then-chain.png) +![](promise-then-chain.svg) The whole thing works, because a call to `promise.then` returns a promise, so that we can call the next `.then` on it. When a handler returns a value, it becomes the result of that promise, so the next `.then` is called with it. -To make these words more clear, here's the start of the chain: - -```js run -new Promise(function(resolve, reject) { - - setTimeout(() => resolve(1), 1000); - -}).then(function(result) { - - alert(result); - return result * 2; // <-- (1) - -}) // <-- (2) -// .then… -``` - -The value returned by `.then` is a promise, that's why we are able to add another `.then` at `(2)`. When the value is returned in `(1)`, that promise becomes resolved, so the next handler runs with the value. - **A classic newbie error: technically we can also add many `.then` to a single promise. This is not chaining.** For example: @@ -94,7 +76,7 @@ What we did here is just several handlers to one promise. They don't pass the re Here's the picture (compare it with the chaining above): -![](promise-then-many.png) +![](promise-then-many.svg) All `.then` on the same promise get the same result -- the result of that promise. So in the code above all `alert` show the same: `1`. @@ -102,9 +84,9 @@ In practice we rarely need multiple handlers for one promise. Chaining is used m ## Returning promises -Normally, a value returned by a `.then` handler is immediately passed to the next handler. But there's an exception. +A handler, used in `.then(handler)` may create and return a promise. -If the returned value is a promise, then the further execution is suspended until it settles. After that, the result of that promise is given to the next `.then` handler. +In that case further handlers wait till it settles, and then get its result. For instance: @@ -138,15 +120,15 @@ new Promise(function(resolve, reject) { }); ``` -Here the first `.then` shows `1` returns `new Promise(…)` in the line `(*)`. After one second it resolves, and the result (the argument of `resolve`, here it's `result*2`) is passed on to handler of the second `.then` in the line `(**)`. It shows `2` and does the same thing. +Here the first `.then` shows `1` and returns `new Promise(…)` in the line `(*)`. After one second it resolves, and the result (the argument of `resolve`, here it's `result * 2`) is passed on to handler of the second `.then`. That handler is in the line `(**)`, it shows `2` and does the same thing. -So the output is again 1 -> 2 -> 4, but now with 1 second delay between `alert` calls. +So the output is the same as in the previous example: 1 -> 2 -> 4, but now with 1 second delay between `alert` calls. Returning promises allows us to build chains of asynchronous actions. ## Example: loadScript -Let's use this feature with the promisified `loadScript`, defined in the [previous chapter](/promise-basics#loadscript), to load scripts one by one, in sequence: +Let's use this feature with the promisified `loadScript`, defined in the [previous chapter](info:promise-basics#loadscript), to load scripts one by one, in sequence: ```js run loadScript("/article/promise-chaining/one.js") @@ -184,7 +166,7 @@ Here each `loadScript` call returns a promise, and the next `.then` runs when it We can add more asynchronous actions to the chain. Please note that code is still "flat", it grows down, not to the right. There are no signs of "pyramid of doom". -Please note that technically we can add `.then` directly to each `loadScript`, like this: +Technically, we could add `.then` directly to each `loadScript`, like this: ```js run loadScript("/article/promise-chaining/one.js").then(script1 => { @@ -207,9 +189,7 @@ Sometimes it's ok to write `.then` directly, because the nested function has acc ````smart header="Thenables" -To be precise, `.then` may return an arbitrary "thenable" object, and it will be treated the same way as a promise. - -A "thenable" object is any object with a method `.then`. +To be precise, a handler may return not exactly a promise, but a so-called "thenable" object - an arbitrary object that has method `.then`, and it will be treated the same way as a promise. The idea is that 3rd-party libraries may implement "promise-compatible" objects of their own. They can have extended set of methods, but also be compatible with native promises, because they implement `.then`. @@ -229,7 +209,9 @@ class Thenable { new Promise(resolve => resolve(1)) .then(result => { +*!* return new Thenable(result); // (*) +*/!* }) .then(alert); // shows 2 after 1000ms ``` @@ -244,7 +226,7 @@ This feature allows to integrate custom objects with promise chains without havi In frontend programming promises are often used for network requests. So let's see an extended example of that. -We'll use the [fetch](mdn:api/WindowOrWorkerGlobalScope/fetch) method to load the information about the user from the remote server. The method is quite complex, it has many optional parameters, but the basic usage is quite simple: +We'll use the [fetch](info:fetch) method to load the information about the user from the remote server. It has a lot of optional parameters covered in [separate chapters](info:fetch), but the basic syntax is quite simple: ```js let promise = fetch(url); @@ -261,7 +243,7 @@ fetch('/article/promise-chaining/user.json') // .then below runs when the remote server responds .then(function(response) { // response.text() returns a new promise that resolves with the full response text - // when we finish downloading it + // when it loads return response.text(); }) .then(function(text) { @@ -278,7 +260,7 @@ We'll also use arrow functions for brevity: // same as above, but response.json() parses the remote content as JSON fetch('/article/promise-chaining/user.json') .then(response => response.json()) - .then(user => alert(user.name)); // iliakan + .then(user => alert(user.name)); // iliakan, got user name ``` Now let's do something with the loaded user. @@ -319,7 +301,7 @@ fetch('/article/promise-chaining/user.json') .then(user => fetch(`https://api.github.com/users/${user.name}`)) .then(response => response.json()) *!* - .then(githubUser => new Promise(function(resolve, reject) { + .then(githubUser => new Promise(function(resolve, reject) { // (*) */!* let img = document.createElement('img'); img.src = githubUser.avatar_url; @@ -329,7 +311,7 @@ fetch('/article/promise-chaining/user.json') setTimeout(() => { img.remove(); *!* - resolve(githubUser); + resolve(githubUser); // (**) */!* }, 3000); })) @@ -337,9 +319,11 @@ fetch('/article/promise-chaining/user.json') .then(githubUser => alert(`Finished showing ${githubUser.name}`)); ``` -Now right after `setTimeout` runs `img.remove()`, it calls `resolve(githubUser)`, thus passing the control to the next `.then` in the chain and passing forward the user data. +That is, `.then` handler in the line `(*)` now returns `new Promise`, that becomes settled only after the call of `resolve(githubUser)` in `setTimeout` `(**)`. + +The next `.then` in chain will wait for that. -As a rule, an asynchronous action should always return a promise. +As a good rule, an asynchronous action should always return a promise. That makes it possible to plan actions after it. Even if we don't plan to extend the chain now, we may need it later. @@ -384,4 +368,4 @@ If a `.then` (or `catch/finally`, doesn't matter) handler returns a promise, the Here's a full picture: -![](promise-handler-variants.png) +![](promise-handler-variants.svg) diff --git a/1-js/11-async/03-promise-chaining/promise-handler-variants-2.png b/1-js/11-async/03-promise-chaining/promise-handler-variants-2.png deleted file mode 100644 index 712f57b82..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-handler-variants-2.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-handler-variants-2@2x.png b/1-js/11-async/03-promise-chaining/promise-handler-variants-2@2x.png deleted file mode 100644 index 5b57be809..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-handler-variants-2@2x.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-handler-variants.png b/1-js/11-async/03-promise-chaining/promise-handler-variants.png deleted file mode 100644 index 2643fde89..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-handler-variants.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-handler-variants.svg b/1-js/11-async/03-promise-chaining/promise-handler-variants.svg new file mode 100644 index 000000000..192f59348 --- /dev/null +++ b/1-js/11-async/03-promise-chaining/promise-handler-variants.svg @@ -0,0 +1 @@ +return valuereturn promisethrow errorstate: "fulfilled" result: valuestate: "rejected" result: error...with the result of the new promise...state: "pending" result: undefinedthe call of .then(handler) always returns a promise:if handler ends with…that promise settles with: \ No newline at end of file diff --git a/1-js/11-async/03-promise-chaining/promise-handler-variants@2x.png b/1-js/11-async/03-promise-chaining/promise-handler-variants@2x.png deleted file mode 100644 index 313e241cc..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-handler-variants@2x.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-then-chain.png b/1-js/11-async/03-promise-chaining/promise-then-chain.png deleted file mode 100644 index fab8a92ad..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-then-chain.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-then-chain.svg b/1-js/11-async/03-promise-chaining/promise-then-chain.svg new file mode 100644 index 000000000..631ad64a7 --- /dev/null +++ b/1-js/11-async/03-promise-chaining/promise-then-chain.svg @@ -0,0 +1 @@ +.thennew Promiseresolve(1)return 2.thenreturn 4.then \ No newline at end of file diff --git a/1-js/11-async/03-promise-chaining/promise-then-chain@2x.png b/1-js/11-async/03-promise-chaining/promise-then-chain@2x.png deleted file mode 100644 index 421b59359..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-then-chain@2x.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-then-many.png b/1-js/11-async/03-promise-chaining/promise-then-many.png deleted file mode 100644 index b13d20a9e..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-then-many.png and /dev/null differ diff --git a/1-js/11-async/03-promise-chaining/promise-then-many.svg b/1-js/11-async/03-promise-chaining/promise-then-many.svg new file mode 100644 index 000000000..a50359e5f --- /dev/null +++ b/1-js/11-async/03-promise-chaining/promise-then-many.svg @@ -0,0 +1 @@ +.thennew Promiseresolve(1).then.then \ No newline at end of file diff --git a/1-js/11-async/03-promise-chaining/promise-then-many@2x.png b/1-js/11-async/03-promise-chaining/promise-then-many@2x.png deleted file mode 100644 index f0609c946..000000000 Binary files a/1-js/11-async/03-promise-chaining/promise-then-many@2x.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/article.md b/1-js/11-async/04-promise-error-handling/article.md index 3424d099e..624c7e812 100644 --- a/1-js/11-async/04-promise-error-handling/article.md +++ b/1-js/11-async/04-promise-error-handling/article.md @@ -1,11 +1,9 @@ # Error handling with promises -Asynchronous actions may sometimes fail: in case of an error the corresponding promise becomes rejected. For instance, `fetch` fails if the remote server is not available. We can use `.catch` to handle errors (rejections). +Promise chains are great at error handling. When a promise rejects, the control jumps to the closest rejection handler. That's very convenient in practice. -Promise chaining is great at that aspect. When a promise rejects, the control jumps to the closest rejection handler down the chain. That's very convenient in practice. - -For instance, in the code below the URL is wrong (no such site) and `.catch` handles the error: +For instance, in the code below the URL to `fetch` is wrong (no such site) and `.catch` handles the error: ```js run *!* @@ -15,17 +13,9 @@ fetch('https://no-such-server.blabla') // rejects .catch(err => alert(err)) // TypeError: failed to fetch (the text may vary) ``` -Or, maybe, everything is all right with the site, but the response is not valid JSON: +As you can see, the `.catch` doesn't have to be immediate. It may appear after one or maybe several `.then`. -```js run -fetch('/') // fetch works fine now, the server responds with the HTML page -*!* - .then(response => response.json()) // rejects: the page is HTML, not a valid json -*/!* - .catch(err => alert(err)) // SyntaxError: Unexpected token < in JSON at position 0 -``` - -The easiest way to catch all errors is to append `.catch` to the end of chain: +Or, maybe, everything is all right with the site, but the response is not valid JSON. The easiest way to catch all errors is to append `.catch` to the end of chain: ```js run fetch('/article/promise-chaining/user.json') @@ -48,7 +38,7 @@ fetch('/article/promise-chaining/user.json') */!* ``` -Normally, `.catch` doesn't trigger at all, because there are no errors. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it. +Normally, such `.catch` doesn't trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it. ## Implicit try..catch @@ -74,9 +64,9 @@ new Promise((resolve, reject) => { }).catch(alert); // Error: Whoops! ``` -The "invisible `try..catch`" around the executor automatically catches the error and treats it as a rejection. +The "invisible `try..catch`" around the executor automatically catches the error and turns it into rejected promise. -This happens not only in the executor, but in its handlers as well. If we `throw` inside a `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler. +This happens not only in the executor function, but in its handlers as well. If we `throw` inside a `.then` handler, that means a rejected promise, so the control jumps to the nearest error handler. Here's an example: @@ -106,7 +96,7 @@ The final `.catch` not only catches explicit rejections, but also occasional err ## Rethrowing -As we already noticed, `.catch` behaves like `try..catch`. We may have as many `.then` handlers as we want, and then use a single `.catch` at the end to handle errors in all of them. +As we already noticed, `.catch` at the end of the chain is similar to `try..catch`. We may have as many `.then` handlers as we want, and then use a single `.catch` at the end to handle errors in all of them. In a regular `try..catch` we can analyze the error and maybe rethrow it if can't handle. The same thing is possible for promises. @@ -150,7 +140,7 @@ new Promise((resolve, reject) => { } }).then(function() { - /* never runs here */ + /* doesn't run here */ }).catch(error => { // (**) alert(`The unknown error has occurred: ${error}`); @@ -159,101 +149,11 @@ new Promise((resolve, reject) => { }); ``` -Then the execution jumps from the first `.catch` `(*)` to the next one `(**)` down the chain. - -In the section below we'll see a practical example of rethrowing. - -## Fetch error handling example - -Let's improve error handling for the user-loading example. - -The promise returned by [fetch](mdn:api/WindowOrWorkerGlobalScope/fetch) rejects when it's impossible to make a request. For instance, a remote server is not available, or the URL is malformed. But if the remote server responds with error 404, or even error 500, then it's considered a valid response. - -What if the server returns a non-JSON page with error 500 in the line `(*)`? What if there's no such user, and GitHub returns a page with error 404 at `(**)`? - -```js run -fetch('no-such-user.json') // (*) - .then(response => response.json()) - .then(user => fetch(`https://api.github.com/users/${user.name}`)) // (**) - .then(response => response.json()) - .catch(alert); // SyntaxError: Unexpected token < in JSON at position 0 - // ... -``` - - -As of now, the code tries to load the response as JSON no matter what and dies with a syntax error. You can see that by running the example above, as the file `no-such-user.json` doesn't exist. - -That's not good, because the error just falls through the chain, without details: what failed and where. - -So let's add one more step: we should check the `response.status` property that has HTTP status, and if it's not 200, then throw an error. - -```js run -class HttpError extends Error { // (1) - constructor(response) { - super(`${response.status} for ${response.url}`); - this.name = 'HttpError'; - this.response = response; - } -} - -function loadJson(url) { // (2) - return fetch(url) - .then(response => { - if (response.status == 200) { - return response.json(); - } else { - throw new HttpError(response); - } - }) -} - -loadJson('no-such-user.json') // (3) - .catch(alert); // HttpError: 404 for .../no-such-user.json -``` - -1. We make a custom class for HTTP Errors to distinguish them from other types of errors. Besides, the new class has a constructor that accepts `response` object and saves it in the error. So error-handling code will be able to access the response. -2. Then we put together the requesting and error-handling code into a function that fetches the `url` *and* treats any non-200 status as an error. That's convenient, because we often need such logic. -3. Now `alert` shows a more helpful descriptive message. - -The great thing about having our own class for errors is that we can easily check for it in error-handling code using `instanceof`. - -For instance, we can make a request, and then if we get 404 -- ask the user to modify the information. - -The code below loads a user with the given name from GitHub. If there's no such user, then it asks for the correct name: - -```js run -function demoGithubUser() { - let name = prompt("Enter a name?", "iliakan"); - - return loadJson(`https://api.github.com/users/${name}`) - .then(user => { - alert(`Full name: ${user.name}.`); - return user; - }) - .catch(err => { -*!* - if (err instanceof HttpError && err.response.status == 404) { -*/!* - alert("No such user, please reenter."); - return demoGithubUser(); - } else { - throw err; // (*) - } - }); -} - -demoGithubUser(); -``` - -Please note: `.catch` here catches all errors, but it "knows how to handle" only `HttpError 404`. In that particular case it means that there's no such user, and `.catch` just retries in that case. - -For other errors, it has no idea what could go wrong. Maybe a programming error or something. So it just rethrows it in the line `(*)`. +The execution jumps from the first `.catch` `(*)` to the next one `(**)` down the chain. ## Unhandled rejections -What happens when an error is not handled? For instance, after the rethrow `(*)` in the example above. - -Or we could just forget to append an error handler to the end of the chain, like here: +What happens when an error is not handled? For instance, we forgot to append `.catch` to the end of the chain, like here: ```js untrusted run refresh new Promise(function() { @@ -264,13 +164,13 @@ new Promise(function() { }); // without .catch at the end! ``` -In case of an error, the promise state becomes "rejected", and the execution should jump to the closest rejection handler. But there is no such handler in the examples above. So the error gets "stuck". There's no code to handle it. +In case of an error, the promise becomes rejected, and the execution should jump to the closest rejection handler. But there is none. So the error gets "stuck". There's no code to handle it. -In practice, just like with a regular unhandled errors, it means that something has terribly gone wrong. +In practice, just like with regular unhandled errors in code, it means that something has terribly gone wrong. -What happens when a regular error occurs and is not caught by `try..catch`? The script dies. Similar thing happens with unhandled promise rejections. +What happens when a regular error occurs and is not caught by `try..catch`? The script dies with a message in console. Similar thing happens with unhandled promise rejections. -The JavaScript engine tracks such rejections and generates a global error in that case. You can see it in the console if you run the example above. +JavaScript engine tracks such rejections and generates a global error in that case. You can see it in the console if you run the example above. In the browser we can catch such errors using the event `unhandledrejection`: @@ -294,52 +194,11 @@ If an error occurs, and there's no `.catch`, the `unhandledrejection` handler tr Usually such errors are unrecoverable, so our best way out is to inform the user about the problem and probably report the incident to the server. -In non-browser environments like Node.js there are other similar ways to track unhandled errors. - +In non-browser environments like Node.js there are other ways to track unhandled errors. ## Summary -- `.catch` handles promise rejections of all kinds: be it a `reject()` call, or an error thrown in a handler. -- We should place `.catch` exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and rethrow unknown ones. +- `.catch` handles errors in promises of all kinds: be it a `reject()` call, or an error thrown in a handler. +- We should place `.catch` exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and rethrow unknown ones (maybe they are programming mistakes). - It's ok not to use `.catch` at all, if there's no way to recover from an error. - In any case we should have the `unhandledrejection` event handler (for browsers, and analogs for other environments), to track unhandled errors and inform the user (and probably our server) about the them, so that our app never "just dies". - -And finally, if we have load-indication, then `.finally` is a great handler to stop it when the fetch is complete: - -```js run -function demoGithubUser() { - let name = prompt("Enter a name?", "iliakan"); - -*!* - document.body.style.opacity = 0.3; // (1) start the indication -*/!* - - return loadJson(`https://api.github.com/users/${name}`) -*!* - .finally(() => { // (2) stop the indication - document.body.style.opacity = ''; - return new Promise(resolve => setTimeout(resolve)); // (*) - }) -*/!* - .then(user => { - alert(`Full name: ${user.name}.`); - return user; - }) - .catch(err => { - if (err instanceof HttpError && err.response.status == 404) { - alert("No such user, please reenter."); - return demoGithubUser(); - } else { - throw err; - } - }); -} - -demoGithubUser(); -``` - -Here on the line `(1)` we indicate loading by dimming the document. The method doesn't matter, could use any type of indication instead. - -When the promise is settled, be it a successful fetch or an error, `finally` triggers at the line `(2)` and stops the indication. - -There's a little browser trick `(*)` with returning a zero-timeout promise from `finally`. That's because some browsers (like Chrome) need "a bit time" outside promise handlers to paint document changes. So it ensures that the indication is visually stopped before going further on the chain. diff --git a/1-js/11-async/04-promise-error-handling/promise-handler-variants-2.png b/1-js/11-async/04-promise-error-handling/promise-handler-variants-2.png deleted file mode 100644 index 712f57b82..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-handler-variants-2.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-handler-variants-2@2x.png b/1-js/11-async/04-promise-error-handling/promise-handler-variants-2@2x.png deleted file mode 100644 index 5b57be809..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-handler-variants-2@2x.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-handler-variants.png b/1-js/11-async/04-promise-error-handling/promise-handler-variants.png deleted file mode 100644 index 2643fde89..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-handler-variants.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-handler-variants@2x.png b/1-js/11-async/04-promise-error-handling/promise-handler-variants@2x.png deleted file mode 100644 index 313e241cc..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-handler-variants@2x.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-then-chain.png b/1-js/11-async/04-promise-error-handling/promise-then-chain.png deleted file mode 100644 index fab8a92ad..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-then-chain.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-then-chain.svg b/1-js/11-async/04-promise-error-handling/promise-then-chain.svg new file mode 100644 index 000000000..631ad64a7 --- /dev/null +++ b/1-js/11-async/04-promise-error-handling/promise-then-chain.svg @@ -0,0 +1 @@ +.thennew Promiseresolve(1)return 2.thenreturn 4.then \ No newline at end of file diff --git a/1-js/11-async/04-promise-error-handling/promise-then-chain@2x.png b/1-js/11-async/04-promise-error-handling/promise-then-chain@2x.png deleted file mode 100644 index 421b59359..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-then-chain@2x.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-then-many.png b/1-js/11-async/04-promise-error-handling/promise-then-many.png deleted file mode 100644 index b13d20a9e..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-then-many.png and /dev/null differ diff --git a/1-js/11-async/04-promise-error-handling/promise-then-many.svg b/1-js/11-async/04-promise-error-handling/promise-then-many.svg new file mode 100644 index 000000000..a50359e5f --- /dev/null +++ b/1-js/11-async/04-promise-error-handling/promise-then-many.svg @@ -0,0 +1 @@ +.thennew Promiseresolve(1).then.then \ No newline at end of file diff --git a/1-js/11-async/04-promise-error-handling/promise-then-many@2x.png b/1-js/11-async/04-promise-error-handling/promise-then-many@2x.png deleted file mode 100644 index f0609c946..000000000 Binary files a/1-js/11-async/04-promise-error-handling/promise-then-many@2x.png and /dev/null differ diff --git a/1-js/11-async/05-promise-api/article.md b/1-js/11-async/05-promise-api/article.md index ed071910c..5db47b664 100644 --- a/1-js/11-async/05-promise-api/article.md +++ b/1-js/11-async/05-promise-api/article.md @@ -2,65 +2,6 @@ There are 5 static methods in the `Promise` class. We'll quickly cover their use cases here. -## Promise.resolve - -The syntax: - -```js -let promise = Promise.resolve(value); -``` - -Returns a resolved promise with the given `value`. - -Same as: - -```js -let promise = new Promise(resolve => resolve(value)); -``` - -The method is used when we already have a value, but would like to have it "wrapped" into a promise. - -For instance, the `loadCached` function below fetches the `url` and remembers the result, so that future calls on the same URL return it immediately: - -```js -function loadCached(url) { - let cache = loadCached.cache || (loadCached.cache = new Map()); - - if (cache.has(url)) { -*!* - return Promise.resolve(cache.get(url)); // (*) -*/!* - } - - return fetch(url) - .then(response => response.text()) - .then(text => { - cache.set(url,text); - return text; - }); -} -``` - -We can use `loadCached(url).then(…)`, because the function is guaranteed to return a promise. That's the purpose `Promise.resolve` serves in the line `(*)`: it makes sure the interface is unified. We can always use `.then` after `loadCached`. - -## Promise.reject - -The syntax: - -```js -let promise = Promise.reject(error); -``` - -Create a rejected promise with the `error`. - -Same as: - -```js -let promise = new Promise((resolve, reject) => reject(error)); -``` - -We cover it here for completeness, rarely used in real code. - ## Promise.all Let's say we want to run many promises to execute in parallel, and wait till all of them are ready. @@ -75,9 +16,9 @@ The syntax is: let promise = Promise.all([...promises...]); ``` -It takes an array of promises (technically can be any iterable, but usually an array) and returns a new promise. +`Promise.all` takes an array of promises (technically can be any iterable, but usually an array) and returns a new promise. -The new promise resolves when all listed promises are settled and has an array of their results. +The new promise resolves when all listed promises are settled and the array of their results becomes its result. For instance, the `Promise.all` below settles after 3 seconds, and then its result is an array `[1, 2, 3]`: @@ -89,7 +30,7 @@ Promise.all([ ]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member ``` -Please note that the relative order is the same. Even though the first promise takes the longest time to resolve, it is still first in the array of results. +Please note that the order of resulting array members is the same as source promises. Even though the first promise takes the longest time to resolve, it's still first in the array of results. A common trick is to map an array of job data into an array of promises, and then wrap that into `Promise.all`. @@ -112,7 +53,7 @@ Promise.all(requests) )); ``` -A bigger example with fetching user information for an array of github users by their names (or we could fetch an array of goods by their ids, the logic is same): +A bigger example with fetching user information for an array of GitHub users by their names (we could fetch an array of goods by their ids, the logic is same): ```js run let names = ['iliakan', 'remy', 'jeresig']; @@ -121,7 +62,7 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`)); Promise.all(requests) .then(responses => { - // all responses are ready, we can show HTTP status codes + // all responses are resolved successfully for(let response of responses) { alert(`${response.url}: ${response.status}`); // shows 200 for every url } @@ -134,7 +75,7 @@ Promise.all(requests) .then(users => users.forEach(user => alert(user.name))); ``` -**If any of the promises is rejected, `Promise.all` immediately rejects with that error.** +**If any of the promises is rejected, the promise returned by `Promise.all` immediately rejects with that error.** For instance: @@ -155,11 +96,11 @@ If one promise rejects, `Promise.all` immediately rejects, completely forgetting For example, if there are multiple `fetch` calls, like in the example above, and one fails, other ones will still continue to execute, but `Promise.all` don't watch them any more. They will probably settle, but the result will be ignored. -`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](fetch-abort) we'll cover `AbortController` that aims to help with that, but it's not a part of the Promise API. +`Promise.all` does nothing to cancel them, as there's no concept of "cancellation" in promises. In [another chapter](info:fetch-abort) we'll cover `AbortController` that can help with that, but it's not a part of the Promise API. ``` -````smart header="`Promise.all(...)` allows non-promise items in `iterable`" -Normally, `Promise.all(...)` accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's wrapped in `Promise.resolve`. +````smart header="`Promise.all(iterable)` allows non-promise \"regular\" values in `iterable`" +Normally, `Promise.all(...)` accepts an iterable (in most cases an array) of promises. But if any of those objects is not a promise, it's passed to the resulting array "as is". For instance, here the results are `[1, 2, 3]`: @@ -168,35 +109,34 @@ Promise.all([ new Promise((resolve, reject) => { setTimeout(() => resolve(1), 1000) }), - 2, // treated as Promise.resolve(2) - 3 // treated as Promise.resolve(3) + 2, + 3 ]).then(alert); // 1, 2, 3 ``` -So we are able to pass non-promise values to `Promise.all` where convenient. - +So we are able to pass ready values to `Promise.all` where convenient. ```` ## Promise.allSettled [recent browser="new"] -`Promise.all` rejects as a whole if any promise rejects. That's good in cases, when we need *all* results to go on: +`Promise.all` rejects as a whole if any promise rejects. That's good for "all or nothing" cases, when we need *all* results to go on: ```js Promise.all([ fetch('/template.html'), fetch('/style.css'), fetch('/data.json') -]).then(render); // render method needs them all +]).then(render); // render method needs results of all fetches ``` -`Promise.allSettled` waits for all promises to settle: even if one rejects, it waits for the others. The resulting array has: +`Promise.allSettled` waits for all promises to settle. The resulting array has: - `{status:"fulfilled", value:result}` for successful responses, - `{status:"rejected", reason:error}` for errors. -For example, we'd like to fetch the information about multiple users. Even if one request fails, we're interested in the others. +For example, we'd like to fetch the information about multiple users. Even if one request fails, we're still interested in the others. Let's use `Promise.allSettled`: @@ -229,7 +169,7 @@ The `results` in the line `(*)` above will be: ] ``` -So, for each promise we get its status and `value/reason`. +So, for each promise we get its status and `value/error`. ### Polyfill @@ -238,18 +178,18 @@ If the browser doesn't support `Promise.allSettled`, it's easy to polyfill: ```js if(!Promise.allSettled) { Promise.allSettled = function(promises) { - return Promise.all(promises.map(p => Promise.resolve(p).then(v => ({ + return Promise.all(promises.map(p => Promise.resolve(p).then(value => ({ state: 'fulfilled', - value: v, - }), r => ({ + value + }), reason => ({ state: 'rejected', - reason: r, + reason })))); }; } ``` -In this code, `promises.map` takes input values, turns into promises (just in case a non-promise was passed) with `p => Promise.resolve(p)`, and then adds `.then` handler to it. +In this code, `promises.map` takes input values, turns into promises (just in case a non-promise was passed) with `p => Promise.resolve(p)`, and then adds `.then` handler to every one. That handler turns a successful result `v` into `{state:'fulfilled', value:v}`, and an error `r` into `{state:'rejected', reason:r}`. That's exactly the format of `Promise.allSettled`. @@ -257,7 +197,7 @@ Then we can use `Promise.allSettled` to get the results or *all* given promises, ## Promise.race -Similar to `Promise.all`, it takes an iterable of promises, but instead of waiting for all of them to finish, it waits for the first result (or error), and goes on with it. +Similar to `Promise.all`, but waits only for the first settled promise, and gets its result (or error). The syntax is: @@ -275,18 +215,70 @@ Promise.race([ ]).then(alert); // 1 ``` -So, the first result/error becomes the result of the whole `Promise.race`. After the first settled promise "wins the race", all further results/errors are ignored. +The first promise here was fastest, so it became the result. After the first settled promise "wins the race", all further results/errors are ignored. + + +## Promise.resolve/reject + +Methods `Promise.resolve` and `Promise.reject` are rarely needed in modern code, because `async/await` syntax (we'll cover it in [a bit later](info:async-await)) makes them somewhat obsolete. + +We cover them here for completeness, and for those who can't use `async/await` for some reason. + +- `Promise.resolve(value)` creates a resolved promise with the result `value`. + +Same as: + +```js +let promise = new Promise(resolve => resolve(value)); +``` + +The method is used for compatibility, when a function is expected to return a promise. + +For example, `loadCached` function below fetches URL and remembers (caches) its content. For future calls with the same URL it immediately gets the previous content from cache, but uses `Promise.resolve` to make a promise of it, so that the returned value is always a promise: + +```js +let cache = new Map(); + +function loadCached(url) { + if (cache.has(url)) { +*!* + return Promise.resolve(cache.get(url)); // (*) +*/!* + } + + return fetch(url) + .then(response => response.text()) + .then(text => { + cache.set(url,text); + return text; + }); +} +``` + +We can write `loadCached(url).then(…)`, because the function is guaranteed to return a promise. We can always use `.then` after `loadCached`. That's the purpose of `Promise.resolve` in the line `(*)`. + +### Promise.reject + +- `Promise.reject(error)` creates a rejected promise with `error`. + +Same as: + +```js +let promise = new Promise((resolve, reject) => reject(error)); +``` + +In practice, this method is almost never used. ## Summary There are 5 static methods of `Promise` class: -1. `Promise.resolve(value)` -- makes a resolved promise with the given value. -2. `Promise.reject(error)` -- makes a rejected promise with the given error. -3. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, then it becomes the error of `Promise.all`, and all other results are ignored. -4. `Promise.allSettled(promises)` (a new method) -- waits for all promises to resolve or reject and returns an array of their results as object with: - - `state`: `'fulfilled'` or `'rejected'` +1. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, then it becomes the error of `Promise.all`, and all other results are ignored. +2. `Promise.allSettled(promises)` (recently added method) -- waits for all promises to settle and returns their results as array of objects with: + - `state`: `"fulfilled"` or `"rejected"` - `value` (if fulfilled) or `reason` (if rejected). -5. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome. +3. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome. +4. `Promise.resolve(value)` -- makes a resolved promise with the given value. +5. `Promise.reject(error)` -- makes a rejected promise with the given error. -Of these five, `Promise.all/allSettled` are the most common in practice. +Of these five, `Promise.all` is probably the most common in practice. diff --git a/1-js/11-async/06-promisify/article.md b/1-js/11-async/06-promisify/article.md index 7c84912b5..6d91c0490 100644 --- a/1-js/11-async/06-promisify/article.md +++ b/1-js/11-async/06-promisify/article.md @@ -2,8 +2,6 @@ Promisification -- is a long word for a simple transform. It's conversion of a function that accepts a callback into a function returning a promise. -To be more precise, we create a wrapper-function that does the same, internally calling the original one, but returns a promise. - Such transforms are often needed in real-life, as many functions and libraries are callback-based. But promises are more convenient. So it makes sense to promisify those. For instance, we have `loadScript(src, callback)` from the chapter . @@ -23,7 +21,7 @@ function loadScript(src, callback) { // loadScript('path/script.js', (err, script) => {...}) ``` -Let's promisify it. The new `loadScriptPromise(src)` function will do the same, but accept only `src` (no callback) and return a promise. +Let's promisify it. The new `loadScriptPromise(src)` function will do the same, but accept only `src` (no `callback`) and return a promise. ```js let loadScriptPromise = function(src) { @@ -39,13 +37,13 @@ let loadScriptPromise = function(src) { // loadScriptPromise('path/script.js').then(...) ``` -Now `loadScriptPromise` fits well in our promise-based code. +Now `loadScriptPromise` fits well in promise-based code. As we can see, it delegates all the work to the original `loadScript`, providing its own callback that translates to promise `resolve/reject`. -As we may need to promisify many functions, it makes sense to use a helper. +In practice we'll probably need to promisify many functions, it makes sense to use a helper. -That's actually very simple -- `promisify(f)` below takes a to-promisify function `f` and returns a wrapper function. +We'll call it `promisify(f)`: it accepts a to-promisify function `f` and returns a wrapper function. That wrapper does the same as in the code above: returns a promise and passes the call to the original `f`, tracking the result in a custom callback: @@ -61,7 +59,7 @@ function promisify(f) { } } - args.push(callback); // append our custom callback to the end of arguments + args.push(callback); // append our custom callback to the end of f arguments f.call(this, ...args); // call the original function }); @@ -75,9 +73,9 @@ loadScriptPromise(...).then(...); Here we assume that the original function expects a callback with two arguments `(err, result)`. That's what we encounter most often. Then our custom callback is in exactly the right format, and `promisify` works great for such a case. -But what if the original `f` expects a callback with more arguments `callback(err, res1, res2)`? +But what if the original `f` expects a callback with more arguments `callback(err, res1, res2, ...)`? -Here's a modification of `promisify` that returns an array of multiple callback results: +Here's a more advanced version of `promisify`: if called as `promisify(f, true)`, the promise result will be an array of callback results `[res1, res2, ...]`: ```js // promisify(f, true) to get array of results @@ -105,7 +103,7 @@ f = promisify(f, true); f(...).then(arrayOfResults => ..., err => ...) ``` -In some cases, `err` may be absent at all: `callback(result)`, or there's something exotic in the callback format, then we can promisify such functions without using the helper, manually. +For more exotic callback formats, like those without `err` at all: `callback(result)`, we can promisify such functions without using the helper, manually. There are also modules with a bit more flexible promisification functions, e.g. [es6-promisify](https://github.com/digitaldesignlabs/es6-promisify). In Node.js, there's a built-in `util.promisify` function for that. diff --git a/1-js/11-async/07-microtask-queue/article.md b/1-js/11-async/07-microtask-queue/article.md index 0ea6fef4d..f444e21ce 100644 --- a/1-js/11-async/07-microtask-queue/article.md +++ b/1-js/11-async/07-microtask-queue/article.md @@ -1,5 +1,5 @@ -# Microtasks and event loop +# Microtasks Promise handlers `.then`/`.catch`/`.finally` are always asynchronous. @@ -10,18 +10,18 @@ Here's the demo: ```js run let promise = Promise.resolve(); -promise.then(() => alert("promise done")); +promise.then(() => alert("promise done!")); alert("code finished"); // this alert shows first ``` -If you run it, you see `code finished` first, and then `promise done`. +If you run it, you see `code finished` first, and then `promise done!`. That's strange, because the promise is definitely done from the beginning. Why did the `.then` trigger afterwards? What's going on? -## Microtasks +## Microtasks queue Asynchronous tasks need proper management. For that, the standard specifies an internal queue `PromiseJobs`, more often referred to as "microtask queue" (v8 term). @@ -34,7 +34,7 @@ Or, to say that simply, when a promise is ready, its `.then/catch/finally` handl That's why "code finished" in the example above shows first. -![](promiseQueue.png) +![](promiseQueue.svg) Promise handlers always go through that internal queue. @@ -52,140 +52,61 @@ Promise.resolve() Now the order is as intended. -## Event loop - -In-browser JavaScript execution flow, as well as Node.js, is based on an *event loop*. - -"Event loop" is a process when the engine sleeps and waits for events. When they occur - handles them and sleeps again. - -Events may come either from external sources, like user actions, or just as the end signal of an internal task. - -Examples of events: -- `mousemove`, a user moved their mouse. -- `setTimeout` handler is to be called. -- an external ` ``` -Here we can see it in the browser, but the same is true for any module. - ### Module-level scope Each module has its own top-level scope. In other words, top-level variables and functions from a module are not seen in other scripts. @@ -82,7 +83,7 @@ In the example below, two scripts are imported, and `hello.js` tries to use `use Modules are expected to `export` what they want to be accessible from outside and `import` what they need. -So we should import `user.js` directly into `hello.js` instead of `index.html`. +So we should import `user.js` into `hello.js` and get the required functionality from it instead of relying on global variables. That's the correct variant: @@ -125,10 +126,10 @@ alert("Module is evaluated!"); import `./alert.js`; // Module is evaluated! // 📁 2.js -import `./alert.js`; // (nothing) +import `./alert.js`; // (shows nothing) ``` -In practice, top-level module code is mostly used for initialization. We create data structures, pre-fill them, and if we want something to be reusable -- export it. +In practice, top-level module code is mostly used for initialization, creation of internal data structures, and if we want something to be reusable -- export it. Now, a more advanced example. @@ -160,9 +161,9 @@ alert(admin.name); // Pete */!* ``` -So, let's reiterate -- the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the `admin` object, other modules will see that . +So, let's reiterate -- the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the `admin` object, other modules will see that. -Such behavior is great for modules that require configuration. We can set required properties on the first import, and then in further imports it's ready. +Such behavior allows to *configure* modules on first import. We can setup its properties once, and then in further imports it's ready. For instance, `admin.js` module may provide certain functionality, but expect the credentials to come into the `admin` object from outside: @@ -175,7 +176,7 @@ export function sayHi() { } ``` -Now, in `init.js`, the first script of our app, we set `admin.name`. Then everyone will see it, including calls made from inside `admin.js` itself: +In `init.js`, the first script of our app, we set `admin.name`. Then everyone will see it, including calls made from inside `admin.js` itself: ```js // 📁 init.js @@ -183,6 +184,8 @@ import {admin} from './admin.js'; admin.name = "Pete"; ``` +Another module can also see `admin.name`: + ```js // 📁 other.js import {admin, sayHi} from './admin.js'; @@ -204,11 +207,13 @@ Its content depends on the environment. In the browser, it contains the url of t ``` -### Top-level "this" is undefined +### In a module, "this" is undefined That's kind of a minor feature, but for completeness we should mention it. -In a module, top-level `this` is undefined, as opposed to a global object in non-module scripts: +In a module, top-level `this` is undefined. + +Compare it to non-module scripts, where `this` is a global object: ```html run height=0 ``` -2. External scripts that are fetched from another domain require [CORS](mdn:Web/HTTP/CORS) headers. In other words, if a module script is fetched from another domain, the remote server must supply a header `Access-Control-Allow-Origin: *` (may use fetching domain instead of `*`) to indicate that the fetch is allowed. +2. External scripts that are fetched from another origin (e.g. another site) require [CORS](mdn:Web/HTTP/CORS) headers, as described in the chapter . In other words, if a module script is fetched from another origin, the remote server must supply a header `Access-Control-Allow-Origin` allowing the fetch. ```html @@ -332,13 +339,6 @@ Old browsers do not understand `type="module"`. Scripts of the unknown type are ``` -If we use bundle tools, then as scripts are bundled together into a single file (or few files), `import/export` statements inside those scripts are replaced by special bundler functions. So the resulting "bundled" script does not contain any `import/export`, it doesn't require `type="module"`, and we can put it into a regular script: - -```html - - -``` - ## Build tools In real-life, browser modules are rarely used in their "raw" form. Usually, we bundle them together with a special tool such as [Webpack](https://webpack.js.org/) and deploy to the production server. @@ -357,13 +357,20 @@ Build tools do the following: - Modern, bleeding-edge JavaScript syntax may be transformed to older one with similar functionality using [Babel](https://babeljs.io/). - The resulting file is minified (spaces removed, variables replaced with shorter named etc). +If we use bundle tools, then as scripts are bundled together into a single file (or few files), `import/export` statements inside those scripts are replaced by special bundler functions. So the resulting "bundled" script does not contain any `import/export`, it doesn't require `type="module"`, and we can put it into a regular script: + +```html + + +``` + That said, native modules are also usable. So we won't be using Webpack here: you can configure it later. ## Summary To summarize, the core concepts are: -1. A module is a file. To make `import/export` work, browsers need ` -```smart header="Edge spaces and in-between empty text are usually hidden in tools" +```smart header="Spaces at string start/end and space-only text nodes are usually hidden in tools" Browser tools (to be covered soon) that work with DOM usually do not show spaces at the start/end of the text and empty text nodes (line-breaks) between tags. -That's because they are mainly used to decorate HTML, and do not affect how it is shown (in most cases). +Developer tools save screen space this way. -On further DOM pictures we'll sometimes omit them where they are irrelevant, to keep things short. +On further DOM pictures we'll sometimes omit them when they are irrelevant. Such spaces usually do not affect how the document is displayed. ``` - ## Autocorrection If the browser encounters malformed HTML, it automatically corrects it when making DOM. @@ -106,7 +117,7 @@ drawHtmlTree(node3, 'div.domtree', 690, 150); While generating the DOM, browsers automatically process errors in the document, close tags and so on. -Such an document with unclosed tags: +Such document with unclosed tags: ```html no-beautify

Hello @@ -148,7 +159,9 @@ You see? The `` appeared out of nowhere. You should keep this in mind whi ## Other node types -Let's add more tags and a comment to the page: +There are some other node types besides elements and text nodes. + +For example, comments: ```html @@ -174,7 +187,7 @@ let node6 = {"name":"HTML","nodeType":1,"children":[{"name":"HEAD","nodeType":1, drawHtmlTree(node6, 'div.domtree', 690, 500); -Here we see a new tree node type -- *comment node*, labeled as `#comment`. +We can see here a new tree node type -- *comment node*, labeled as `#comment`, between two text nodes. We may think -- why is a comment added to the DOM? It doesn't affect the visual representation in any way. But there's a rule -- if something's in HTML, then it also must be in the DOM tree. @@ -195,8 +208,6 @@ There are [12 node types](https://dom.spec.whatwg.org/#node). In practice we usu To see the DOM structure in real-time, try [Live DOM Viewer](http://software.hixie.ch/utilities/js/live-dom-viewer/). Just type in the document, and it will show up DOM at an instant. -## In the browser inspector - Another way to explore the DOM is to use the browser developer tools. Actually, that's what we use when developing. To do so, open the web-page [elks.html](elks.html), turn on the browser developer tools and switch to the Elements tab. @@ -225,10 +236,12 @@ The best way to study them is to click around. Most values are editable in-place ## Interaction with console -As we explore the DOM, we also may want to apply JavaScript to it. Like: get a node and run some code to modify it, to see the result. Here are few tips to travel between the Elements tab and the console. +As we work the DOM, we also may want to apply JavaScript to it. Like: get a node and run some code to modify it, to see the result. Here are few tips to travel between the Elements tab and the console. -- Select the first `

  • ` in the Elements tab. -- Press `key:Esc` -- it will open console right below the Elements tab. +For the start: + +1. Select the first `
  • ` in the Elements tab. +2. Press `key:Esc` -- it will open console right below the Elements tab. Now the last selected element is available as `$0`, the previously selected is `$1` etc. @@ -236,9 +249,11 @@ We can run commands on them. For instance, `$0.style.background = 'red'` makes t ![](domconsole0.png) -From the other side, if we're in console and have a variable referencing a DOM node, then we can use the command `inspect(node)` to see it in the Elements pane. +That's how to get a node from Elements in Console. + +There's also a road back. If there's a variable referencing a DOM node, then we can use the command `inspect(node)` in Console to see it in the Elements pane. -Or we can just output it in the console and explore "at-place", like `document.body` below: +Or we can just output DOM-node in the console and explore "at-place", like `document.body` below: ![](domconsole1.png) diff --git a/2-ui/1-document/02-dom-nodes/statusbarButtonGlyphs.svg b/2-ui/1-document/02-dom-nodes/statusbarButtonGlyphs.svg deleted file mode 100644 index fa37b2cc3..000000000 --- a/2-ui/1-document/02-dom-nodes/statusbarButtonGlyphs.svg +++ /dev/null @@ -1 +0,0 @@ -! \ No newline at end of file diff --git a/2-ui/1-document/03-dom-navigation/3-navigation-links-which-null/solution.md b/2-ui/1-document/03-dom-navigation/3-navigation-links-which-null/solution.md index 266d26b1b..d76936320 100644 --- a/2-ui/1-document/03-dom-navigation/3-navigation-links-which-null/solution.md +++ b/2-ui/1-document/03-dom-navigation/3-navigation-links-which-null/solution.md @@ -1,5 +1,5 @@ 1. Yes, true. The element `elem.lastChild` is always the last one, it has no `nextSibling`. -2. No, wrong, because `elem.children[0]` is the first child *among elements*. But there may exist non-element nodes before it. So `previousSibling` may be a text node. Also, if there are no children, then trying to access `elem.children[0]` +2. No, wrong, because `elem.children[0]` is the first child *among elements*. But there may exist non-element nodes before it. So `previousSibling` may be a text node. Please note: for both cases if there are no children, then there will be an error. diff --git a/2-ui/1-document/03-dom-navigation/article.md b/2-ui/1-document/03-dom-navigation/article.md index be5a6531b..80cefd1cc 100644 --- a/2-ui/1-document/03-dom-navigation/article.md +++ b/2-ui/1-document/03-dom-navigation/article.md @@ -9,11 +9,11 @@ libs: The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object. -All operations on the DOM start with the `document` object. From it we can access any node. +All operations on the DOM start with the `document` object. That's the main "entry point" to DOM. From it we can access any node. Here's a picture of links that allow for travel between DOM nodes: -![](dom-links.png) +![](dom-links.svg) Let's discuss them in more detail. @@ -86,9 +86,9 @@ For instance, here `` has children `
    ` and `