diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..d3877a5382
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+* text=auto eol=lf
+*.svg binary
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000000..490051876d
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: iliakan
diff --git a/.gitignore b/.gitignore
index 6f90fd1907..1a71fb7c82 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,4 @@ sftp-config.json
Thumbs.db
+/svgs
\ No newline at end of file
diff --git a/1-js/01-getting-started/1-intro/article.md b/1-js/01-getting-started/1-intro/article.md
index b2c304475a..37b7b1157e 100644
--- a/1-js/01-getting-started/1-intro/article.md
+++ b/1-js/01-getting-started/1-intro/article.md
@@ -1,9 +1,14 @@
# JavaScript 入門
+<<<<<<< HEAD
JavaScript について、何が特別なのか、それを使ってできることや他のどの技術と上手くやるのか見てみましょう。
+=======
+Let's see what's so special about JavaScript, what we can achieve with it, and what other technologies play well with it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## JavaScript とは?
+<<<<<<< HEAD
*JavaScript* は当初 *"Webページを活かすため"* に作られました。
この言語のプログラムは *スクリプト* と呼ばれます。それらはHTMLの中に書かれ、ページが読み込まれると自動的に実行されます。
@@ -31,23 +36,68 @@ JavaScript が作られたとき, 当初は別の名前を持っていました:
これらの用語は、インターネット上の開発者の記事で使用されているため、覚えておくと良いでしょう。 たとえば、"ある機能 X がV8でサポートされている" と言った場合、おそらくChromeとOperaで動作します。
```smart header="エンジンはどのように動く?"
+=======
+*JavaScript* was initially created to "make web pages alive".
+
+The programs in this language are called *scripts*. They can be written right in a web page's HTML and run automatically as the page loads.
+
+Scripts are provided and executed as plain text. They don't need special preparation or compilation to run.
+
+In this aspect, JavaScript is very different from another language called [Java](https://en.wikipedia.org/wiki/Java_(programming_language)).
+
+```smart header="Why is it called JavaScript?"
+When JavaScript was created, it initially had another name: "LiveScript". But Java was very popular at that time, so it was decided that positioning a new language as a "younger brother" of Java would help.
+
+But as it evolved, JavaScript became a fully independent language with its own specification called [ECMAScript](http://en.wikipedia.org/wiki/ECMAScript), and now it has no relation to Java at all.
+```
+
+Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called [the JavaScript engine](https://en.wikipedia.org/wiki/JavaScript_engine).
+
+The browser has an embedded engine sometimes called a "JavaScript virtual machine".
+
+Different engines have different "codenames". For example:
+
+- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome, Opera and Edge.
+- [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- in Firefox.
+- ...There are other codenames like "Chakra" for IE, "JavaScriptCore", "Nitro" and "SquirrelFish" for Safari, etc.
+
+The terms above are good to remember because they are used in developer articles on the internet. We'll use them too. For instance, if "a feature X is supported by V8", then it probably works in Chrome, Opera and Edge.
+
+```smart header="How do engines work?"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
エンジンは複雑ですが、基本は単純です。
+<<<<<<< HEAD
1. エンジン (ブラウザの場合は組み込まれています) はスクリプトを読み("パース")ます。
2. その後、スクリプトを機械語に変換("コンパイル")します。
3. 機械語が実行されます。非常に早く動作します。
エンジンは処理の各ステップで最適化を行います。実行時にコンパイルされたスクリプトも見ており、そこを流れるデータを分析し、それ基づいて機械語を最適化します。 最終的に、スクリプトはとても速く実行されます。
+=======
+1. The engine (embedded if it's a browser) reads ("parses") the script.
+2. Then it converts ("compiles") the script to machine code.
+3. And then the machine code runs, pretty fast.
+
+The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and further optimizes the machine code based on that knowledge.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
## ブラウザ内のJavaScriptができることは?
+<<<<<<< HEAD
モダンなJavaScriptは "安全な" プログラミング言語です。それは、メモリやCPUのような低レベルのアクセスは提供しません。なぜなら、当初はそれらを必要としないブラウザ用に作成されたものだからです。
JavaScript の機能は、実行される環境に大きく依存します。 例えば、[Node.js](https://wikipedia.org/wiki/Node.js) では、JavaScriptが任意のファイルを読み書きしたりできる機能をサポートしています。
ブラウザ内のJavaScriptは、Webページの操作、ユーザやWebサーバとのやり取りに関する様々なことを実行できます。
+=======
+Modern JavaScript is a "safe" programming language. It does not provide low-level access to memory or the CPU, because it was initially created for browsers which do not require it.
+
+JavaScript's capabilities greatly depend on the environment it's running in. For instance, [Node.js](https://wikipedia.org/wiki/Node.js) supports functions that allow JavaScript to read/write arbitrary files, perform network requests, etc.
+
+In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
たとえば、ブラウザ内のJavaScriptは次のようなことが可能です:
@@ -58,15 +108,24 @@ JavaScript の機能は、実行される環境に大きく依存します。
- クライアント側でデータを記憶する("ローカルストレージ")。
+<<<<<<< HEAD
## ブラウザ内のJavaScriptで出来ないことは?
ブラウザでは、JavaScriptの機能はユーザの安全のために制限されています。
その目的は、悪意のあるWebページがプライベートな情報へアクセスしたり、ユーザデータへ危害を加えることを防ぐことです。
制限の例として、次のようなものがあります:
+=======
+JavaScript's abilities in the browser are limited to protect the user's safety. The aim is to prevent an evil webpage from accessing private information or harming the user's data.
+
+Examples of such restrictions include:
+
+- JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS functions.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- Webページ上のJavaScriptは、ハードディスク上の任意のファイルの読み書きや、それらのコピー、プログラムの実行をすることができません。OSのシステム機能に直接アクセスすることはできません。
+<<<<<<< HEAD
現代のブラウザは、ファイルを扱うことはできますがアクセスは制限されており、ブラウザウィンドウへのファイルの "ドロップ" や、`` タグを経由したファイル選択と言ったユーザの特定の操作のみを提供しています。
カメラ/マイクやその他デバイスとやり取りする方法はありますが、ユーザの明示的な許可が求められます。したがって、JavaScriptが有効なページがWebカメラを密かに有効にしたり、それを利用して利用者の周囲を観察したり、[NSA](https://en.wikipedia.org/wiki/National_Security_Agency) に情報を送信すると言ったことはできません。
@@ -77,8 +136,21 @@ JavaScript の機能は、実行される環境に大きく依存します。
この制限もユーザの安全のためです。ユーザが開いた `http://anysite.com` というサイトのページは、URL `http://gmail.com` の別のブラウザのタブにアクセスし、そこから情報を盗むことはできません。
- JavaScriptはネットワークを介して、現在のページがきたサーバと簡単にやり取りすることができます。しかし、他のサイト/ドメインからデータを受信することは制限されています。可能ですが、リモート側からの明示的な同意(HTTPヘッダで表現)が必要になります。繰り返しますが、これらは安全上の制限です。
+
+=======
+ There are ways to interact with the camera/microphone and other devices, but they require a user's explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the [NSA](https://en.wikipedia.org/wiki/National_Security_Agency).
+- Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other page if they come from different sites (from a different domain, protocol or port).
+
+ This is called the "Same Origin Policy". To work around that, *both pages* must agree for data exchange and must contain special JavaScript code that handles it. We'll cover that in the tutorial.
+
+ 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`, for example, 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.
+

+Such limitations do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugins/extensions which may ask for extended permissions.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
+
JavaScriptがブラウザ外で使われる場合はこのような制限は存在しません。たとえば、サーバ上です。また、現代のブラウザは、より拡張されたアクセス権限を必要とするプラグイン/拡張機能を利用することもできます。
## なにがJavaScriptを特別なものにしている?
@@ -86,11 +158,19 @@ JavaScriptがブラウザ外で使われる場合はこのような制限は存
JavaScriptには少なくとも *3つ* の素晴らしいことがあります:
```compare
+<<<<<<< HEAD
+ HTML/CSSとの完全な統合
+ シンプルなことはシンプルに
+ すべてのメジャーブラウザでサポートされており、デフォルトで有効
+=======
++ Full integration with HTML/CSS.
++ Simple things are done simply.
++ Supported by all major browsers and enabled by default.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
+JavaScript is the only browser technology that combines these three things.
+<<<<<<< HEAD
JavaScriptは、これら3つのことを組み合わせた唯一のブラウザテクノロジーです。
それがJavaScriptをユニークなものにしています。だからこそ、ブラウザインターフェイスを作成するための最も普及しているツールとなっています。
@@ -98,6 +178,11 @@ JavaScriptは、これら3つのことを組み合わせた唯一のブラウザ
とは言え、JavaScript を利用してサーバやモバイルアプリケーションなどを作成することもできます。
## JavaScriptを "覆う" 言語
+=======
+That's what makes JavaScript unique. That's why it's the most widespread tool for creating browser interfaces.
+
+That said, JavaScript can be used to create servers, mobile applications, etc.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
JavaScriptの構文は、すべての人のニーズにマッチしている訳ではありません。人によって求める機能は異なります。
@@ -105,9 +190,15 @@ JavaScriptの構文は、すべての人のニーズにマッチしている訳
そのため、最近では新しい言語が数多く登場しています。これらはブラウザで実行する前にJavaScriptに *トランスパイル* (変換)されます。
+<<<<<<< HEAD
最新のツールは非常に高速にトランスパイルでき、透過的です。開発者が別の言語でコードを作成し、それを自動変換することができます。
これは、そのような言語の例です:
+=======
+So, recently a plethora of new languages appeared, which are *transpiled* (converted) to JavaScript before they run in the browser.
+
+Modern tools make the transpilation very fast and transparent, actually allowing developers to code in another language and auto-converting it "under the hood".
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- [CoffeeScript](http://coffeescript.org/) はJavaScriptの "シンタックスシュガー"です。より短い構文を導入し、より簡潔でクリアなコードを書くことができます。たいてい、Ruby 開発者は好きです。
- [TypeScript](http://www.typescriptlang.org/) は "厳密なデータ型指定" の追加に焦点をあてています。それは複雑なシステムの開発とサポートを簡素化するためです。これは Microsoftにより開発されています。
@@ -115,6 +206,7 @@ JavaScriptの構文は、すべての人のニーズにマッチしている訳
- [Dart](https://www.dartlang.org/) はブラウザ以外の環境(モバイルアプリのような)で動作する独自のエンジンを持ったスタンドアローンな言語ですが、JavaScript へトランスパイルすることもできます。Googleによって開発されました。
- [Brython](https://brython.info/) は JavaScript への Python トランスパイラで、JavaScript を使用することなく、純粋な Python でアプリケーションを作成することができます。
+<<<<<<< HEAD
他にもあります。もちろん、上記のような言語を利用する予定だとしても、実際に行われていることを本当に理解するためにJavaScriptは知っておくのがよいです。
## サマリ
@@ -122,3 +214,19 @@ JavaScriptの構文は、すべての人のニーズにマッチしている訳
- JavaScriptは当初ブラウザ用の言語として作られました。しかし今はその他の多くの環境で利用されています。
- 現時点では、JavaScriptはHTML/CSSと完全に統合し、最も広く採用されたブラウザ言語として、独立した地位にいます。
- JavaScriptに "トランスパイル" し、特定の機能を提供する多くの言語があります。 JavaScriptをマスターした後、少なくとも簡単にでも目を通しておくことをお勧めします。
+=======
+- [CoffeeScript](https://coffeescript.org/) is "syntactic sugar" for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it.
+- [TypeScript](https://www.typescriptlang.org/) is concentrated on adding "strict data typing" to simplify the development and support of complex systems. It is developed by Microsoft.
+- [Flow](https://flow.org/) also adds data typing, but in a different way. Developed by Facebook.
+- [Dart](https://www.dartlang.org/) is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google.
+- [Brython](https://brython.info/) is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript.
+- [Kotlin](https://kotlinlang.org/docs/reference/js-overview.html) is a modern, concise and safe programming language that can target the browser or Node.
+
+There are more. Of course, even if we use one of these transpiled languages, we should also know JavaScript to really understand what we're doing.
+
+## Summary
+
+- JavaScript was initially created as a browser-only language, but it is now used in many other environments as well.
+- Today, JavaScript has a unique position as the most widely-adopted browser language, fully integrated with HTML/CSS.
+- There are many languages that get "transpiled" to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 794bccbd80..6f4dcb7b92 100644
--- a/1-js/01-getting-started/2-manuals-specifications/article.md
+++ b/1-js/01-getting-started/2-manuals-specifications/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# マニュアルと仕様
この本は *チュートリアル* であり、あなたが徐々に言語を学ぶのを助けることを目的としています。そのため、基本が理解できたら別の情報源が必要になってきます。
@@ -39,3 +40,41 @@ JavaScript は開発中の言語であり、定期的に新機能が追加され
これらのリソースは、言語の詳細やサポートなどに関する貴重な情報が含まれているため、実際の開発に役立ちます。
特定の機能に関する詳細な情報が必要な場合は、それら(またはこのページ)を覚えておいてください。
+=======
+# Manuals and specifications
+
+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 resources.
+
+## Specification
+
+[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, the specification is the right place. But it's not for everyday use.
+
+A new specification version is released every year. Between these releases, the latest specification draft is 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 developing for the browser, then there are other specifications covered in the [second part](info:browser-environment) of the tutorial.
+
+## Manuals
+
+- **MDN (Mozilla) JavaScript Reference** is the main manual with examples and other information. It's great to get in-depth information about individual language functions, methods etc.
+
+ You can find it at .
+
+Although, it's often best to use an internet search instead. Just use "MDN [term]" in the query, e.g. to search for the `parseInt` function.
+
+## Compatibility tables
+
+JavaScript is a developing language, new features get added regularly.
+
+To see their support among browser-based and other engines, see:
+
+- - per-feature tables of support, e.g. to see which engines support modern cryptography functions: .
+- - a table with language features and engines that support those or don't support.
+
+All these resources are useful in real-life development, as they contain valuable information about language details, their support, etc.
+
+Please remember them (or this page) for the cases when you need in-depth information about a particular feature.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/01-getting-started/3-code-editors/article.md b/1-js/01-getting-started/3-code-editors/article.md
index 2536271d99..356e0d3262 100644
--- a/1-js/01-getting-started/3-code-editors/article.md
+++ b/1-js/01-getting-started/3-code-editors/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# コードエディタ
コードエディタはプログラマが最も時間を費やす場所です。
@@ -44,3 +45,54 @@ Windows には、"Visual Studio"もあります。"Visual Studio Code" と混同
この広い世界には他にも素晴らしいエディタがあります。ぜひあなたが最も好きなものを選んでください。
エディタの選択は、他のツールのようにプロジェクト、習慣や個人の趣向によります。
+=======
+# Code editors
+
+A code editor is the place where programmers spend most of their time.
+
+There are two main types of code editors: IDEs and lightweight editors. Many people use one tool of each type.
+
+## IDE
+
+The term [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) (Integrated Development Environment) refers to a powerful editor with many features that usually operates on a "whole project." As the name suggests, it's not just an editor, but a full-scale "development environment."
+
+An IDE loads the project (which can be many files), allows navigation between files, provides autocompletion based on the whole project (not just the open file), and integrates with a version management system (like [git](https://git-scm.com/)), a testing environment, and other "project-level" stuff.
+
+If you haven't selected an IDE yet, consider the following options:
+
+- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free).
+- [WebStorm](https://www.jetbrains.com/webstorm/) (cross-platform, paid).
+
+For Windows, there's also "Visual Studio", not to be confused with "Visual Studio Code". "Visual Studio" is a paid and mighty Windows-only editor, well-suited for the .NET platform. It's also good at JavaScript. There's also a free version [Visual Studio Community](https://www.visualstudio.com/vs/community/).
+
+Many IDEs are paid, but have a trial period. Their cost is usually negligible compared to a qualified developer's salary, so just choose the best one for you.
+
+## Lightweight editors
+
+"Lightweight editors" are not as powerful as IDEs, but they're fast, elegant and simple.
+
+They are mainly used to open and edit a file instantly.
+
+The main difference between a "lightweight editor" and an "IDE" is that an IDE works on a project-level, so it loads much more data on start, analyzes the project structure if needed and so on. A lightweight editor is much faster if we need only one file.
+
+In practice, lightweight editors may have a lot of plugins including directory-level syntax analyzers and autocompleters, so there's no strict border between a lightweight editor and an IDE.
+
+There are many options, for instance:
+
+- [Sublime Text](https://www.sublimetext.com/) (cross-platform, shareware).
+- [Notepad++](https://notepad-plus-plus.org/) (Windows, free).
+- [Vim](https://www.vim.org/) and [Emacs](https://www.gnu.org/software/emacs/) are also cool if you know how to use them.
+
+## Let's not argue
+
+The editors in the lists above are those that either I or my friends whom I consider good developers have been using for a long time and are happy with.
+
+There are other great editors in our big world. Please choose the one you like the most.
+
+The choice of an editor, like any other tool, is individual and depends on your projects, habits, and personal preferences.
+
+The author's personal opinion:
+
+- I'd use [Visual Studio Code](https://code.visualstudio.com/) if I develop mostly frontend.
+- Otherwise, if it's mostly another language/platform and partially frontend, then consider other editors, such as XCode (Mac), Visual Studio (Windows) or Jetbrains family (Webstorm, PHPStorm, RubyMine etc, depending on the language).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/01-getting-started/4-devtools/article.md b/1-js/01-getting-started/4-devtools/article.md
index 7e78a2e23a..2ab2b1d12c 100644
--- a/1-js/01-getting-started/4-devtools/article.md
+++ b/1-js/01-getting-started/4-devtools/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 開発者コンソール
コードにエラーはつきものです。少なくともあなたが [ロボット](https://en.wikipedia.org/wiki/Bender_(Futurama)) ではなく人間であるなら、*絶対に* 間違いをする、ということです。
@@ -61,3 +62,68 @@ Preferencesを開き、"Advanced" ペインに行きます。一番下にチェ
- Windows下では、ほとんどのブラウザは `key:F12` で開くことができます。Mac用のChromeは `key:Cmd+Opt+J` が必要で、Safariは`key:Cmd+Opt+C`です(最初に有効化が必要)。
これで環境が整いました。次のセクションでは、JavaScriptの説明に入ります。
+=======
+# Developer console
+
+Code is prone to errors. You will quite likely make errors... Oh, what am I talking about? You are *absolutely* going to make errors, at least if you're a human, not a [robot](https://en.wikipedia.org/wiki/Bender_(Futurama)).
+
+But in the browser, users don't see errors by default. So, if something goes wrong in the script, we won't see what's broken and can't fix it.
+
+To see errors and get a lot of other useful information about scripts, "developer tools" have been embedded in browsers.
+
+Most developers lean towards Chrome or Firefox for development because those browsers have the best developer tools. Other browsers also provide developer tools, sometimes with special features, but are usually playing "catch-up" to Chrome or Firefox. So most developers have a "favorite" browser and switch to others if a problem is browser-specific.
+
+Developer tools are potent; they have many features. To start, we'll learn how to open them, look at errors, and run JavaScript commands.
+
+## Google Chrome
+
+Open the page [bug.html](bug.html).
+
+There's an error in the JavaScript code on it. It's hidden from a regular visitor's eyes, so let's open developer tools to see it.
+
+Press `key:F12` or, if you're on Mac, then `key:Cmd+Opt+J`.
+
+The developer tools will open on the Console tab by default.
+
+It looks somewhat like this:
+
+
+
+The exact look of developer tools depends on your version of Chrome. It changes from time to time but should be similar.
+
+- Here we can see the red-colored error message. In this case, the script contains an unknown "lalala" command.
+- On the right, there is a clickable link to the source `bug.html:12` with the line number where the error has occurred.
+
+Below the error message, there is a blue `>` symbol. It marks a "command line" where we can type JavaScript commands. Press `key:Enter` to run them.
+
+Now we can see errors, and that's enough for a start. We'll come back to developer tools later and cover debugging more in-depth in the chapter .
+
+```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`. This way one can enter long fragments of JavaScript code.
+```
+
+## Firefox, Edge, and others
+
+Most other browsers use `key:F12` to open developer tools.
+
+The look & feel of them is quite similar. Once you know how to use one of these tools (you can start with Chrome), you can easily switch to another.
+
+## Safari
+
+Safari (Mac browser, not supported by Windows/Linux) is a little bit special here. We need to enable the "Develop menu" first.
+
+Open Settings 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.
+
+## Summary
+
+- Developer tools allow us to see errors, run commands, examine variables, and much more.
+- They can be opened with `key:F12` for most browsers on Windows. Chrome for Mac needs `key:Cmd+Opt+J`, Safari: `key:Cmd+Opt+C` (need to enable first).
+
+Now we have the environment ready. In the next section, we'll get down to JavaScript.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/01-getting-started/4-devtools/chrome.webp b/1-js/01-getting-started/4-devtools/chrome.webp
new file mode 100644
index 0000000000..bdf067079e
Binary files /dev/null and b/1-js/01-getting-started/4-devtools/chrome.webp differ
diff --git a/1-js/01-getting-started/4-devtools/chrome@2.webp b/1-js/01-getting-started/4-devtools/chrome@2.webp
new file mode 100644
index 0000000000..2aeca5898a
Binary files /dev/null and b/1-js/01-getting-started/4-devtools/chrome@2.webp differ
diff --git a/1-js/02-first-steps/01-hello-world/1-hello-alert/solution.md b/1-js/02-first-steps/01-hello-world/1-hello-alert/solution.md
index e69de29bb2..81552913b9 100644
--- a/1-js/02-first-steps/01-hello-world/1-hello-alert/solution.md
+++ b/1-js/02-first-steps/01-hello-world/1-hello-alert/solution.md
@@ -0,0 +1,2 @@
+
+[html src="index.html"]
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 7c49ebbf69..966e16de57 100644
--- a/1-js/02-first-steps/01-hello-world/article.md
+++ b/1-js/02-first-steps/01-hello-world/article.md
@@ -1,5 +1,6 @@
# Hello, world!
+<<<<<<< HEAD
このチュートリアルは、プラットフォームに依存しないJavaScriptのコアについてです。もっと先に、Node.jsや他のプラットフォームについて学びます。
しかし、私たちは今スクリプトを動かすための動作環境が必要です。ちょうどこのチュートリアルはオンラインなので、ブラウザが良い選択肢です。もしも別の環境( Node.js など)に集中する予定がある場合に時間を費やさないように、ここでは、ブラウザ固有のコマンド(`alert`のような)が最小限になるようにします。チュートリアルの[次のパート](/ui) では、ブラウザの JavaScript に焦点を当てます。
@@ -12,6 +13,20 @@
JavaScriptプログラムは、`
```
+<<<<<<< HEAD
それらのコメントは`
```
+<<<<<<< HEAD
ここで `/path/to/script.js` はスクリプトファイルの絶対パスです(サイトルートからの)。また、現在のページからの相対パスで指定することもできます。例えば、`src="script.js"` は現在のフォルダにある `"script.js"` を意味するでしょう。
完全なURLも同様に可能です。たとえば:
+=======
+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"`, just like `src="./script.js"`, would mean a file `"script.js"` in the current folder.
+
+We can give a full URL as well. For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```html
-
+
```
複数のスクリプトを使う場合は、複数のタグを使います:
@@ -92,6 +142,7 @@ JavaScriptプログラムは、`
```
+<<<<<<< HEAD
外部の `` で挿入できます。
ブラウザスクリプトやそれらとWebページとのやり取りについては、学ぶことがまだまだあります。しかし、このチュートリアルのこのパートは JavaScript 言語に専念していることに留意してください。JavaScriptを実行するための方法としてここではブラウザを使っており、オンラインでの読み込みではとても便利ですが、数ある実行方法の1つでしかありません。
+=======
+- We can use a ``.
+
+
+There is much more to learn about browser scripts and their interaction with the webpage. But let's keep in mind that this part of the tutorial is devoted to the JavaScript language, so we shouldn't distract ourselves with browser-specific implementations of it. We'll be using the browser as a way to run JavaScript, which is very convenient for online reading, but only one of many.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/02-structure/article.md b/1-js/02-first-steps/02-structure/article.md
index 66e8da1bec..86cbd34ce8 100644
--- a/1-js/02-first-steps/02-structure/article.md
+++ b/1-js/02-first-steps/02-structure/article.md
@@ -1,22 +1,38 @@
# コード構造
+<<<<<<< HEAD
最初に学ぶことは、コードの基本的な構成要素です。
## 文(命令文)
+=======
+The first thing we'll study is the building blocks of code.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
文は、構文構造でアクションを実行するコマンドです。
私たちはすでに `alert('Hello, world!')` という文を見ており、これは "Hello, world!" というメッセージを表示します。
+<<<<<<< HEAD
コードには必要なだけ文を含めることができ、文はセミコロンで区切ることができます。
たとえば、これは "Hello World" のメッセージを2つのアラートに分けます:
+=======
+We've already seen a statement, `alert('Hello, world!')`, which shows the message "Hello, world!".
+
+We can have as many statements in our code as we want. Statements can be separated with a semicolon.
+
+For example, here we split "Hello World" into two alerts:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
alert('Hello'); alert('World');
```
+<<<<<<< HEAD
通常、それぞれの文は別の行に書かれます。これによりコードの可読性が向上します。
+=======
+Usually, statements are written on separate lines to make the code more readable:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
alert('Hello');
@@ -34,12 +50,20 @@ alert('Hello')
alert('World')
```
+<<<<<<< HEAD
ここで JavaScript は、改行を "暗黙" のセミコロンと解釈します。
これは[自動セミコロン挿入](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion)と呼ばれます。
**ほとんどのケースで改行はセミコロンを意味します。しかし "ほとんどのケース" は "常に" ではありません!**
これは改行はセミコロンを意味しないケースです、例えば:
+=======
+Here, JavaScript interprets the line break as an "implicit" semicolon. This is called an [automatic semicolon insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion).
+
+**In most cases, a newline implies a semicolon. But "in most cases" does not mean "always"!**
+
+There are cases when a newline does not mean a semicolon. For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
alert(3 +
@@ -47,7 +71,11 @@ alert(3 +
+ 2);
```
+<<<<<<< HEAD
このコードは `6` を出力します、なぜなら JavaScript はセミコロンを挿入しないからです。もし行の終わりがプラス `"+"` で終わっている場合、直感的には "不完全な表現" であり、セミコロンが必要ないのは明らかです。このケースでは、それは意図した通りに動作します。
+=======
+The code outputs `6` because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus `"+"`, then it is an "incomplete expression", so a semicolon there would be incorrect. And in this case, that works as intended.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
**しかし本当に必要なときに JavaScriptがセミコロンを想定 "し損なう" ケースがあります。**
@@ -57,38 +85,56 @@ alert(3 +
このようなエラーの具体例に興味があるなら、このコードを確認してみてください:
```js run
-[1, 2].forEach(alert)
+alert("Hello");
+
+[1, 2].forEach(alert);
```
+<<<<<<< HEAD
角括弧 `[]` や `forEach` の意味についてはまだ考える必要はありません。それらについては後ほど勉強するので今のところ問題ではありません。ただ結果を覚えておきましょう: "1", そして "2" が表示されます。
今、コードの前に `alert` を追加し、セミコロンで終わら "ない" ようにしましょう:
+=======
+No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later. For now, just remember the result of running the code: it shows `Hello`, then `1`, then `2`.
+
+Now let's remove the semicolon after the `alert`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
-alert("There will be an error")
+alert("Hello")
-[1, 2].forEach(alert)
+[1, 2].forEach(alert);
```
+<<<<<<< HEAD
実行すると、最初の `alert` だけが表示され、エラーが発生するでしょう!
しかし、`alert` の後にセミコロンをつけた場合はすべてうまく行きます:
```js run
alert("All fine now");
+=======
+The difference compared to the code above is only one character: the semicolon at the end of the first line is gone.
-[1, 2].forEach(alert)
-```
+If we run this code, only the first `Hello` shows (and there's an error, you may need to open the console to see it). There are no numbers any more.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
+That's because JavaScript does not assume a semicolon before square brackets `[...]`. So, the code in the last example is treated as a single statement.
+
+<<<<<<< HEAD
これで "All fine now" メッセージ、そして `1`, `2` が表示されます。
JavaScriptでは角括弧 `[...]` の前にはセミコロンを想定しません。
そのため、セミコロンは自動挿入されないので最初の例のコードは1つの文として扱われます。
エンジンは次のように解釈しています:
+=======
+Here's how the engine sees it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
-alert("There will be an error")[1, 2].forEach(alert)
+alert("Hello")[1, 2].forEach(alert);
```
+<<<<<<< HEAD
しかし、本来は1つではなく2つの文であるべきです。今回のケースのようなマージは間違っているのでエラーです。このようなことが起こる状況は他にもあります。
````
@@ -101,6 +147,22 @@ alert("There will be an error")[1, 2].forEach(alert)
コメントはスクリプトのどの場所にも書くことができます。エンジンはそれらを無視するので、実行には影響しません。
**1行のコメントは、2つのスラッシュ文字 `//` から始まります。**
+=======
+Looks weird, right? Such merging in this case is just wrong. We need to put a semicolon after `alert` for the code to work correctly.
+
+This can happen in other situations also.
+````
+
+We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them.
+
+## Comments [#code-comments]
+
+As time goes on, programs become more and more complex. It becomes necessary to add *comments* which describe what the code does and why.
+
+Comments can be put into any place of a script. They don't affect its execution because the engine simply ignores them.
+
+**One-line comments start with two forward slash characters `//`.**
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
残りの行はコメントです。それは行全体または文に従います。
@@ -124,10 +186,16 @@ alert('Hello');
alert('World');
```
+<<<<<<< HEAD
コメントの内容は無視されます、そのため、/* ... */ の中にコードをおいても実行されません。
これはコードの一部を一時的に無効にしたいときに便利です:
+=======
+The content of comments is ignored, so if we put code inside /* ... */, it won't execute.
+
+Sometimes it can be handy to temporarily disable a part of code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
/* コードのコメントアウト
@@ -136,9 +204,14 @@ alert('Hello');
alert('World');
```
+<<<<<<< HEAD
```smart header="ホットキーを使いましょう!"
ほとんどのエディタでは、コードの行は1行コメントとして `key:Ctrl+/` ホットキーによりコメントアウトすることができます。そして `key:Ctrl+Shift+/` で複数行コメントです(コードの一部を選択し、ホットキーを押します)。
Macでは、 `key:Ctrl` の代わりに `key:Cmd` を試してください。
+=======
+```smart header="Use hotkeys!"
+In most editors, a line of code can be commented out by pressing the `key:Ctrl+/` hotkey for a single-line comment and something like `key:Ctrl+Shift+/` -- for multiline comments (select a piece of code and press the hotkey). For Mac, try `key:Cmd` instead of `key:Ctrl` and `key:Option` instead of `key:Shift`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
````warn header="入れ子のコメントはサポートされていません!"
@@ -156,6 +229,12 @@ alert( 'World' );
コードにコメントするのを躊躇わないでください。
+<<<<<<< HEAD
コメントはコード規模を増加させますが、それは全く問題ではありません。プロダクションサーバへリリースする前にコードを minify する多くのツールがあります。それらはコメントを除去するので、実行されるスクリプトには現れません。そのため、コメント書くことによるネガティブな影響は全くありません。
さらにこのチュートリアルでは、より良いコメントの書き方を説明するチャプター もあります。
+=======
+Comments increase the overall code footprint, but that's not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don't appear in the working scripts. Therefore, comments do not have negative effects on production at all.
+
+Later in the tutorial there will be a chapter that also explains how to write better comments.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 61e00aab05..06bfd23066 100644
--- a/1-js/02-first-steps/03-strict-mode/article.md
+++ b/1-js/02-first-steps/03-strict-mode/article.md
@@ -1,5 +1,6 @@
# モダンなモード, "use strict"
+<<<<<<< HEAD
長い間、JavaScriptは互換性の問題なしに進化していました。新しい機能は言語に追加されましたが、古い機能は変更されませんでした。
それは既存のコードが決して壊れないというメリットがありました。しかし、欠点はJavaScript作成者による間違いや不十分な決定がこの言語から抜け出せなくなったことです。
@@ -7,12 +8,25 @@
ECMAScript 5(ES5) が登場したときは2009年でした。新しい機能が言語に追加され、既存の機能のいくつかが修正されました。古いコードが動作するのを保つために、ほとんどの修正はデフォルトではOFFです。特別なディレクティブ `"use strict"` を明示的に有効にする必要があります。
[cut]
+=======
+For a long time, JavaScript evolved without compatibility issues. New features were added to the language while old functionality didn't change.
+
+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 such modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## "use strict"
+<<<<<<< HEAD
そのディレクティブは文字列のように見えます: `"use strict"` もしくは `'use strict'`。 これがスクリプトの先頭に位置する場合、すべてのスクリプトは "最新の" 方法で動作します。
例えば
+=======
+The directive looks like a string: `"use strict"` or `'use strict'`. When it is located at the top of a script, the whole script works the "modern" way.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
"use strict";
@@ -21,6 +35,7 @@ ECMAScript 5(ES5) が登場したときは2009年でした。新しい機能が
...
```
+<<<<<<< HEAD
私たちはこの後まもなく関数(コマンドをグループ化する方法)を学ぶのでここで言及しますが、`"use strict"` は関数の頭に置くことができることに留意してください。
この場合はその関数内でのみStrictモードが有効になります。しかし通常はスクリプト全体に対して使います。
@@ -32,6 +47,18 @@ ECMAScript 5(ES5) が登場したときは2009年でした。新しい機能が
```js no-strict
alert("some code");
// 下の "use strict" は無視されます, 先頭にある必要があります
+=======
+Quite soon we're going to learn functions (a way to group commands), so let's note in advance that `"use strict"` can be put at the beginning of a function. 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"
+Please make sure that `"use strict"` is at the top of your scripts, otherwise strict mode may not be enabled.
+
+Strict mode isn't enabled here:
+
+```js no-strict
+alert("some code");
+// "use strict" below is ignored--it must be at the top
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
"use strict";
@@ -41,6 +68,7 @@ alert("some code");
コメントだけは `"use strict"` の上に置けます。
````
+<<<<<<< HEAD
```warn header="`use strict` をキャンセルする方法はありません"
`"no use strict"` または同系の古い振る舞いを返すようなディレクティブはありません。
@@ -67,6 +95,33 @@ alert("some code");
もし古いブラウザなどでそれができない場合、いまいちではありますが `use strict` を確実にするための信頼できる方法があります。ラッパーの中に置きます:
+=======
+```warn header="There's no way to cancel `use strict`"
+There is no directive like `"no use strict"` that reverts the engine to old behavior.
+
+Once we enter strict mode, there's no going back.
+```
+
+## Browser console
+
+When you use a [developer console](info:devtools) to run code, please note that it doesn't `use strict` by default.
+
+Sometimes, when `use strict` makes a difference, you'll get incorrect results.
+
+So, how to actually `use strict` in the console?
+
+First, you can try to press `key:Shift+Enter` to input multiple lines, and put `use strict` on top, like this:
+
+```js
+'use strict';
+// ...your code
+
+```
+
+It works in most browsers, namely Firefox and Chrome.
+
+If it doesn't, e.g. in an old browser, there's an ugly, but reliable way to ensure `use strict`. Put it inside this kind of wrapper:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
(function() {
@@ -76,6 +131,7 @@ alert("some code");
})()
```
+<<<<<<< HEAD
## "use strict" は必要?
この質問は明白かもしれませんが、そうではありません。
@@ -91,3 +147,20 @@ alert("some code");
次のチャプターでは、言語の機能を学びながら strict モードと 古いモードの違いについて説明します。幸い、それほど多くありません。そしてそれらは実際に我々の開発をより良くします。
常に `"use strict"` で始まるスクリプトは推奨されます。このチュートリアルのすべての例は、そうでないと明示されていない限り(ほとんどないですが)それを想定しています。
+=======
+## Should we "use strict"?
+
+The question may sound obvious, but it's not so.
+
+One could recommend to start scripts with `"use strict"`... But you know what's cool?
+
+Modern JavaScript supports "classes" and "modules" - advanced language structures (we'll surely get to them), that enable `use strict` automatically. So we don't need to add the `"use strict"` directive, if we use them.
+
+**So, for now `"use strict";` is a welcome guest at the top of your scripts. Later, when your code is all in classes and modules, you may omit it.**
+
+As of now, we've got to know about `use strict` in general.
+
+In the next chapters, as we learn language features, we'll see the differences between the strict and old modes. Luckily, there aren't many and they actually make our lives better.
+
+All examples in this tutorial assume strict mode unless (very rarely) specified otherwise.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 ae6f10cc10..098b771471 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,8 @@
+<<<<<<< HEAD
最初に、我々の惑星の名前に対する変数からです。
+=======
+## The variable for our planet
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
シンプルです:
@@ -6,9 +10,15 @@
let ourPlanetName = "Earth";
```
+<<<<<<< HEAD
注意してください。より短い名前 `planet` を使うことはできますが、どの惑星を指しているかが明白ではありません。より冗長な方がよいです。少なくとも変数が長すぎない程度まで。
2つ目に、現在の訪問者の名前です。:
+=======
+Note, we could use a shorter name `planet`, but it might not be obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
+
+## The name of the current visitor
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let currentUserName = "John";
@@ -18,4 +28,8 @@ let currentUserName = "John";
現代のエディタや自動補完により、長い変数名を簡単に書くことができます。節約は不要です。3単語の名前は良いです。
+<<<<<<< HEAD
また、もしあなたのエディタが適切な自動補完を持っていない場合には、[新しいエディタ](/code-editors) を入手してください。
+=======
+And if your editor does not have proper autocompletion, get [a new one](/code-editors).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/04-variables/2-declare-variables/task.md b/1-js/02-first-steps/04-variables/2-declare-variables/task.md
index 98e33463f7..32e639a78f 100644
--- a/1-js/02-first-steps/04-variables/2-declare-variables/task.md
+++ b/1-js/02-first-steps/04-variables/2-declare-variables/task.md
@@ -4,5 +4,10 @@ importance: 3
# 正しい名前を与える
+<<<<<<< HEAD
1. 我々の惑星の名前を持つ変数を作成してください。あなたはこのような変数の名前をどのように指定しますか?
2. 現在の訪問者の名前を格納する変数を作成してください。あなたはそのような変数の名前をどのように指定しますか?
+=======
+1. Create a variable with the name of our planet. How would you name such a variable?
+2. Create a variable to store the name of a current visitor to a website. How would you name that variable?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 a4785f0a55..120c5839c5 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,8 @@
このコードでは、`birthday` はまさにそうです。なので、大文字を使います。
+<<<<<<< HEAD
対照的に、`age` は実行時に評価されます。 今日はある年齢で、1年後に別の年齢になります。コード実行によって変化しないという意味で一定ですがそれは `birthday` より "定数ではありません"。それは計算されるので、小文字を維持する必要があります。
+=======
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md b/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md
index 6972772cd8..b44b2d20d8 100644
--- a/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md
+++ b/1-js/02-first-steps/04-variables/3-uppercast-constant/task.md
@@ -12,13 +12,19 @@ const birthday = '18.04.1982';
const age = someCode(birthday);
```
+<<<<<<< HEAD
ここで、私たちは定数 `birthday` の日付を持っており、`age` はいくつかのコードの助けを借りて `birthday` から計算されます(詳細はここでは重要ではないため、someCodeの中身はここでは書きません)。
+=======
+Here we have a constant `birthday` for the date, and also the `age` constant.
+
+The `age` is calculated from `birthday` using `someCode()`, which means a function call that we didn't explain yet (we will soon!), but the details don't matter here, the point is that `age` is calculated somehow based on the `birthday`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
`birthday` に対して大文字を使うのは正しいでしょうか? `age` はどうでしょう?
```js
-const BIRTHDAY = '18.04.1982'; // make uppercase?
+const BIRTHDAY = '18.04.1982'; // make birthday uppercase?
-const AGE = someCode(BIRTHDAY); // make uppercase?
+const AGE = someCode(BIRTHDAY); // make age uppercase?
```
diff --git a/1-js/02-first-steps/04-variables/article.md b/1-js/02-first-steps/04-variables/article.md
index 39b8cebac0..2375b9b357 100644
--- a/1-js/02-first-steps/04-variables/article.md
+++ b/1-js/02-first-steps/04-variables/article.md
@@ -1,11 +1,18 @@
# 変数
+<<<<<<< HEAD
ほとんどの場合、JavaScript アプリケーションは情報を処理する必要があります。ここに2つの例があります。
1. オンラインショップ -- 情報は "売られている商品" や "ショッピングカート" などが考えられます。
2. チャットアプリケーション -- 情報は "ユーザ"、"メッセージ" やその他より多くのものが考えられます。
+=======
+Most of the time, a JavaScript application needs to work with information. Here are two examples:
+1. An online shop -- the information might include goods being sold and a shopping cart.
+2. A chat application -- the information might include users, messages, and much more.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
変数は情報を保持するために使われます。
+<<<<<<< HEAD
## 変数
[変数](https://en.wikipedia.org/wiki/Variable_(computer_science)) はデータのための "名前付けされた格納場所" です。私たちは商品や訪問者、その他のデータを格納するために変数が利用できます。
@@ -13,18 +20,35 @@
JavaScriptで変数を作るには、`let` キーワードを使います。
下の文は "message" という名前の変数を作ります(別の言い方: *宣言* または *定義* ):
+=======
+## A variable
+
+A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "named storage" for data. We can use variables to store goodies, visitors, and other data.
+
+To create a variable in JavaScript, use the `let` keyword.
+
+The statement below creates (in other words: *declares*) a variable with the name "message":
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let message;
```
+<<<<<<< HEAD
代入演算子 `=` を使って、データを置く事ができます。
+=======
+Now, we can put some data into it by using the assignment operator `=`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let message;
*!*
+<<<<<<< HEAD
message = 'Hello'; // 文字列を格納します
+=======
+message = 'Hello'; // store the string 'Hello' in the variable named message
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
```
@@ -39,7 +63,11 @@ alert(message); // 変数の中身を表示します
*/!*
```
+<<<<<<< HEAD
簡潔にするために、変数宣言と代入を1行で書くことができます。
+=======
+To be concise, we can combine the variable declaration and assignment into a single line:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let message = 'Hello!'; // 変数宣言と値の代入
@@ -53,7 +81,11 @@ alert(message); // Hello!
let user = 'John', age = 25, message = 'Hello';
```
+<<<<<<< HEAD
より短いように見えるかもしれませんが、これは推奨しません。可読性のため、1変数1行にしてください。
+=======
+That might seem shorter, but we don't recommend it. For the sake of better readability, please use a single line per variable.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
複数行のケースはちょっと長くなりますが、読みやすいです。
@@ -63,7 +95,12 @@ let age = 25;
let message = 'Hello';
```
+<<<<<<< HEAD
多くの変数がある場合、このように書く人もいます:
+=======
+Some people also define multiple variables in this multiline style:
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
let user = 'John',
age = 25,
@@ -78,18 +115,31 @@ let user = 'John'
, message = 'Hello';
```
+<<<<<<< HEAD
技術的にはこれらすべてのパターンは同じです。なので、これは個人の好みと美学の問題です。
````smart header="`let` の代わりに `var`"
古いスクリプトには、別のキーワードがあるかもしれません: `let` の代わりに `var` です:
+=======
+Technically, all these variants do the same thing. So, it's a matter of personal taste and aesthetics.
+
+````smart header="`var` instead of `let`"
+In older scripts, you may also find another keyword: `var` instead of `let`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
*!*var*/!* message = 'Hello';
```
+<<<<<<< HEAD
キーワード `var` は `let` と *ほとんど* 一緒です。それも変数を宣言します。が、わずかに違います, 伝統的スタイルのやり方です。
`let` と `var` には微妙な違いがありますが、まだ気にする必要はありません。その詳細については、 のチャプターで説明します。
+=======
+The `var` keyword is *almost* the same as `let`. It also declares a variable but in a slightly different, "old-school" way.
+
+There are subtle differences between `let` and `var`, but they do not matter to us yet. We'll cover them in detail in the chapter .
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
````
## 現実での例え
@@ -100,7 +150,13 @@ let user = 'John'

+<<<<<<< HEAD
箱の中にはどんな値でも入れることができます。
+=======
+We can put any value in the box.
+
+We can also change it as many times as we want:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
また、それを変えることもできます。値は必要なだけ何度でも変更することができます。
```js run
@@ -134,11 +190,31 @@ alert(hello); // Hello world!
alert(message); // Hello world!
```
+<<<<<<< HEAD
````warn header="2回宣言すると、エラーが発生します"
変数は一度だけ宣言する必要があります。
+=======
+````warn header="Declaring twice triggers an error"
+A variable should be declared only once.
+
+A repeated declaration of the same variable is an error:
+
+```js run
+let message = "This";
+
+// repeated 'let' leads to an error
+let message = "That"; // SyntaxError: 'message' has already been declared
+```
+So, we should declare a variable once and then refer to it without `let`.
+````
+
+```smart header="Functional languages"
+It's interesting to note that there exist so-called [pure functional](https://en.wikipedia.org/wiki/Purely_functional_programming) programming languages, such as [Haskell](https://en.wikipedia.org/wiki/Haskell), that forbid changing variable values.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
同じ変数の繰り替えし宣言はエラーになります:
+<<<<<<< HEAD
```js run
let message = "This";
@@ -154,23 +230,39 @@ let message = "That"; // SyntaxError: 'message' has already been declared
このような言語では、一度"箱の中"に格納された値は、永遠に変化することがありません。もし他の値を"箱の中"に格納したい場合、新たな箱を作る、すなわち新たな変数を宣言する必要があります。一度使った変数を再利用することはできません。
一見すると少し奇妙に見えるかもしれませんが、それらの言語は本格的な開発に適しています。それ以上に、並列計算のような分野ではこの制限が恩恵をもたらしさえします。このような言語を勉強することは視野を広げるために推奨されています(たとえすぐにそれを使う予定がなくても)。
+=======
+Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
## 変数のネーミング
+<<<<<<< HEAD
JavaScript変数名は2つの制限があります:
1. 名前は文字、数字、記号 `$` と `_` のみを含む必要があります。
2. 最初の文字は数字であってはいけません。
変数名の例:
+=======
+There are two limitations on variable names in JavaScript:
+
+1. The name must contain only letters, digits, or the symbols `$` and `_`.
+2. The first character must not be a digit.
+
+Examples of valid names:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let userName;
let test123;
```
+<<<<<<< HEAD
名前に複数の単語を含む場合、[camelCase](https://en.wikipedia.org/wiki/CamelCase) が一般的に使われます。 つまり、単語が続々と続き、各単語は大文字で始まります: `myVeryLongName`.
+=======
+When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word except first starting with a capital letter: `myVeryLongName`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
興味深いことに -- ドル `'$'` や アンダースコア `'_'` も名前に使うことができます。それらは単に文字のように特別な意味をもたない普通の記号です。
@@ -188,6 +280,7 @@ alert($ + _); // 3
```js no-beautify
let 1a; // 数値から開始はできません
+<<<<<<< HEAD
let my-name; // ハイフン '-' は名前で許可されていません
```
@@ -197,12 +290,24 @@ let my-name; // ハイフン '-' は名前で許可されていません
````smart header="英語以外の文字も使用できますが、推奨されません。"
キリル文字や象牙文字を含め、どの言語を使うことも可能です。:
+=======
+let my-name; // hyphens '-' aren't allowed in the name
+```
+
+```smart header="Case matters"
+Variables named `apple` and `APPLE` are two different variables.
+```
+
+````smart header="Non-Latin letters are allowed, but not recommended"
+It is possible to use any language, including Cyrillic letters, Chinese logograms and so on, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let имя = '...';
let 我 = '...';
```
+<<<<<<< HEAD
技術的には、ここでエラーは起きず、このような名前も許可されます。しかし変数名では英語を使うのが国際的な伝統です。たとえ小さなスクリプトを書いているとしても、そのコードはこの先も残るかもしれません。他の国の人々がそれを見ることがあるかもしれません。
````
@@ -210,6 +315,15 @@ let 我 = '...';
[予約語の一覧](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords)があります。これらは言語自身によって使用されるため、変数名として使用することはできません。
たとえば、単語 `let`, `class`, `return`, `function` は予約されています。
+=======
+Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it sometime.
+````
+
+````warn header="Reserved names"
+There is a [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), which cannot be used as variable names because they are used by the language itself.
+
+For example: `let`, `class`, `return`, and `function` are reserved.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
下のコードは構文エラーです:
@@ -221,19 +335,31 @@ let return = 5; // 同様に "return" という名前もエラーです!
````warn header="`use strict` なしでの代入"
+<<<<<<< HEAD
通常、変数を使う前に定義する必要があります。しかし、以前は `let` なしで、単に値を代入するだけで変数を作成することが技術的に可能でした。`use strict` でない場合には今でも動作します。この動作は古いスクリプトの互換性のために維持されています。
+=======
+Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using `let`. This still works now if we don't put `use strict` in our scripts to maintain compatibility with old scripts.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-strict
// 注意: この例は "use strict" なしモードです
+<<<<<<< HEAD
num = 5; // 存在しなかった場合、変数 "num" が作られます
+=======
+num = 5; // the variable "num" is created if it didn't exist
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(num); // 5
```
+<<<<<<< HEAD
これは悪い習慣です、strict モードではエラーになります:
+=======
+This is a bad practice and would cause an error in strict mode:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
-```js run untrusted
+```js
"use strict";
*!*
@@ -244,13 +370,21 @@ num = 5; // エラー: num が未定義です
## 定数
+<<<<<<< HEAD
定数を宣言するためには、 `let` の代わりに `const` を使います。
+=======
+To declare a constant (unchanging) variable, use `const` instead of `let`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
const myBirthday = '18.04.1982';
```
+<<<<<<< HEAD
`const` を使って宣言された変数は "定数" と呼ばれます。それらは変更することが出来ません。変更しようとするとエラーになります:
+=======
+Variables declared using `const` are called "constants". They cannot be reassigned. An attempt to do so would cause an error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
const myBirthday = '18.04.1982';
@@ -258,16 +392,28 @@ const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // エラー, 定数の再代入はできません!
```
+<<<<<<< HEAD
プログラマがその変数は決して変更されるべきでないと確信するとき、それを保証しつつみんなにその事実を明示的に示すために `const` を使います。
+=======
+When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and communicate that fact to everyone.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
### 大文字の定数
+<<<<<<< HEAD
実行する前に分かっているが、覚えるのが難しいという値に対しては、エイリアスとして定数を使うという慣習は広く行われています。
+=======
+There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
このような定数は大文字とアンダースコアを使って名前がつけられます。
+<<<<<<< HEAD
例えば、いわゆる "web"(16進数) 形式での色の定数を作りましょう:
+=======
+For instance, let's make constants for colors in so-called "web" (hexadecimal) format:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
const COLOR_RED = "#F00";
@@ -282,6 +428,7 @@ alert(color); // #FF7F00
メリット:
+<<<<<<< HEAD
- `COLOR_ORANGE` は `"#FF7F00"` よりも覚えるのが遥かに簡単です。
- `COLOR_ORANGE` よりも `"#FF7F00"` のほうがタイプミスをし易いです。
- コードを読むとき、`#FF7F00` よりも `COLOR_ORANGE` のほうがより意味があります。
@@ -291,18 +438,37 @@ alert(color); // #FF7F00
"定数" であることは、その値は決して変わらないことを意味します。が、実行する前に知られている定数(赤の16進数のような)と、実行中にランタイムで *計算* されますが、代入後は変更されないものがあります。
たとえば:
+=======
+- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
+- It is much easier to mistype `"#FF7F00"` than `COLOR_ORANGE`.
+- When reading the code, `COLOR_ORANGE` is much more meaningful than `#FF7F00`.
+
+When should we use capitals for a constant and when should we name it normally? Let's make that clear.
+
+Being a "constant" just means that a variable's value never changes. But some constants are known before execution (like a hexadecimal value for red) and some constants are *calculated* in run-time, during the execution, but do not change after their initial assignment.
+
+For instance:
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
const pageLoadTime = /* webページの読み込み時間 */;
```
+<<<<<<< HEAD
`pageLoadTime` の値はページロードする前にはわからないので、通常の名前がつけられます。しかし代入後は変更されないのでこれも定数です。
つまり、大文字の名前の定数は "ハードコードされた" 値のエイリアスとしてのみ使います。
+=======
+The value of `pageLoadTime` is not known before the page load, so it's named normally. But it's still a constant because it doesn't change after the assignment.
+
+In other words, capital-named constants are only used as aliases for "hard-coded" values.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## 正しい名前をつける
変数について話すとき、もう1つ極めて重要な事があります。
+<<<<<<< HEAD
変数は分かりやすい名前にしてください。必要に応じて考えましょう。
変数のネーミングは、プログラミングにおいて、もっとも重要で複雑なスキルの1つです。変数名をちょっと見れば、どのコードが初心者で書かれ、どれが経験豊富な開発者によって書かれたものかがわかります。
@@ -310,9 +476,19 @@ const pageLoadTime = /* webページの読み込み時間 */;
実際のプロジェクトでは、スクラッチで完全に分離された何かを書くよりも、既存のコードベースの修正や拡張に最も時間を費やします。そして、何か他のことをした後にコードに戻ったとき、よくラベル付けされた情報を探すのははるかに簡単です。それは言い換えると、適切な名前がついている変数、です。
変数を宣言する前に正しい名前について考えるようにしてください。それは多くのことに報いるでしょう。
+=======
+A variable name should have a clean, obvious meaning, describing the data that it stores.
+
+Variable naming is one of the most important and complex skills in programming. A glance at variable names can reveal which code was written by a beginner versus an experienced developer.
+
+In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it's much easier to find information that is well-labelled. Or, in other words, when the variables have good names.
+
+Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
いくつかの良いルールです:
+<<<<<<< HEAD
- `userName` または `shoppingCart` のように人間が読みやすい名前を使ってください。
- 本当に何をしているか分かっている場合を除き、 `a`, `b`, `c` のような略語や短い名前は避けてください。
- 最大限説明的、かつ簡潔な名前を作ってください。悪い名前の例としては `data` や `value` です。このような名前からは何も分かりません。コンテキストからデータや値が意味することが例外的に明白な場合のみ使ってもOKです。
@@ -326,14 +502,34 @@ const pageLoadTime = /* webページの読み込み時間 */;
その結果、変数はステッカーの変更なしに異なったものを投げ入れる箱になります。今何が入っているでしょうか?誰が知っているでしょうか...? より細かくチェックが必要になります。
このようなプログラマは変数定義では多少節約しますが、デバッグで10倍以上の時間を失います。
+=======
+- Use human-readable names like `userName` or `shoppingCart`.
+- Stay away from abbreviations or short names like `a`, `b`, and `c`, unless you know what you're doing.
+- Make names maximally descriptive and concise. Examples of bad names are `data` and `value`. Such names say nothing. It's only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
+- Agree on terms within your team and in your mind. If a site visitor is called a "user" then we should name related variables `currentUser` or `newUser` instead of `currentVisitor` or `newManInTown`.
+
+Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
+
+```smart header="Reuse or create?"
+And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
+
+As a result, their variables are like boxes into which people throw different things without changing their stickers. What's inside the box now? Who knows? We need to come closer and check.
+
+Such programmers save a little bit on variable declaration but lose ten times more on debugging.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
余分な変数は良く、悪ではないです。
+<<<<<<< HEAD
モダンなJavaScriptは minify したり、ブラウザは十分にコードを最適化します。なので、パフォーマンスの問題になることはありません。異なる値に対して異なる変数を使うことは、エンジンの最適化を助けることもあります。
+=======
+Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues. Using different variables for different values can even help the engine optimize your code.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
## サマリ
+<<<<<<< HEAD
データを格納するために変数を宣言することができます。それは `var`, `let`, または `const` を使うことでできます。
- `let` -- は現代の変数宣言です。Chrome(V8)では、`let` を使うには、そのコードは strict モードである必要があります。
@@ -341,3 +537,12 @@ const pageLoadTime = /* webページの読み込み時間 */;
- `const` -- は `let` のようですが、変数の値は変更することができません。
変数は、内部のことを簡単に理解できるように命名するべきです。
+=======
+We can declare variables to store data by using the `var`, `let`, or `const` keywords.
+
+- `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.
+
+Variables should be named in a way that allows us to easily understand what's inside them.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/05-types/article.md b/1-js/02-first-steps/05-types/article.md
index d8c12edb52..4497e39fff 100644
--- a/1-js/02-first-steps/05-types/article.md
+++ b/1-js/02-first-steps/05-types/article.md
@@ -1,10 +1,18 @@
# データ型
+<<<<<<< HEAD
JavaScript の値は常に特定の型です。例えば、文字列や数値です。
JavaScript には8つの基本的なデータ型があります。ここでは基本を学び、次のチャプターでそれらの詳細について話しましょう。
なお、変数はどんなデータでも入れることができます。変数はある時点では文字列で、その後数値を設定することができます:
+=======
+A value in JavaScript is always of a certain type. For example, a string or a number.
+
+There are eight basic data types in JavaScript. Here, we'll cover them in general and in the next chapters we'll talk about each of them in detail.
+
+We can put any type in a variable. For example, a variable can at one moment be a string and then store a number:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// エラーなし
@@ -12,20 +20,34 @@ let message = "hello";
message = 123456;
```
+<<<<<<< HEAD
このようなことができるプログラミング言語は "動的型付け" と呼ばれ、データ型はありますが、変数はそのどれにもバインドされないことを意味します。
## 数値
+=======
+Programming languages that allow such things, such as JavaScript, are called "dynamically typed", meaning that there exist data types, but variables are not bound to any of them.
+
+## Number
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let n = 123;
n = 12.345;
```
+<<<<<<< HEAD
*数値* 型は整数と浮動小数点両方に使われます。
数値に関する多くの操作があります、 e.g. 乗算 `*`, 除算 `/`, 加算 `+`, 減算 `-` など。
通常の数値に加えて、これらのタイプに属する "特別な数値型" もあります。: `Infinity`、 `-Infinity`、 `NaN`.
+=======
+The *number* type represents both integer and floating point numbers.
+
+There are many operations for numbers, e.g. multiplication `*`, division `/`, addition `+`, subtraction `-`, and so on.
+
+Besides regular numbers, there are so-called "special numeric values" which also belong to this data type: `Infinity`, `-Infinity` and `NaN`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- `Infinity` は数学的な[無限大](https://en.wikipedia.org/wiki/Infinity) ∞ を表します。どの値よりも大きい特別な値です。
@@ -35,7 +57,11 @@ n = 12.345;
alert( 1 / 0 ); // 無限大
```
+<<<<<<< HEAD
もしくは、単にコードに直接書くこともできます:
+=======
+ Or just reference it directly:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( Infinity ); // 無限大
@@ -46,12 +72,19 @@ n = 12.345;
alert( "not a number" / 2 ); // NaN, このような除算は誤りです
```
+<<<<<<< HEAD
`NaN` は粘着性です。`NaN` 以降はどのような操作をしても `NaN` になります:
+=======
+ `NaN` is sticky. Any further mathematical operation on `NaN` returns `NaN`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
- alert( "not a number" / 2 + 5 ); // NaN
+ alert( NaN + 1 ); // NaN
+ alert( 3 * NaN ); // NaN
+ alert( "not a number" / 2 - 1 ); // NaN
```
+<<<<<<< HEAD
そのため、数学的な表現の中のどこかに `NaN` がある場合、結果全体に伝搬します。
```smart header="算術演算子は安全です"
@@ -61,9 +94,21 @@ JavaScriptでは数学をするのは安全です。ゼロによる除算、数
```
特別な数値は正式には "数値" 型に所属します。もちろん、常識では数値ではありませんが。
+=======
+ So, if there's a `NaN` somewhere in a mathematical expression, it propagates to the whole result (there's only one exception to that: `NaN ** 0` is `1`).
+
+```smart header="Mathematical operations are safe"
+Doing maths is "safe" in JavaScript. We can do anything: divide by zero, treat non-numeric strings as numbers, etc.
+
+The script will never stop with a fatal error ("die"). At worst, we'll get `NaN` as the result.
+```
+
+Special numeric values formally belong to the "number" type. Of course they are not numbers in the common sense of this word.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
チャプター でより数値の動作について見ていきます。
+<<<<<<< HEAD
## BigInt
JavaScript では、"数値" 型は (253-1) (つまり `9007199254740991`) より大きい、あるいは負値であれば -(253-1) より小さい整数を表現することができません。これらは内部表現に起因する技術的な制限です。
@@ -91,11 +136,44 @@ const bigInt = 1234567890123456789012345678901234567890n;
## 文字列
JavaScriptの文字列は引用符で囲む必要があります。
+=======
+## BigInt [#bigint-type]
+
+In JavaScript, the "number" type cannot safely represent integer values larger than (253-1) (that's `9007199254740991`), or less than -(253-1) for negatives.
+
+To be really precise, the "number" type can store larger integers (up to 1.7976931348623157 * 10308), but outside of the safe integer range ±(253-1) there'll be a precision error, because not all digits fit into the fixed 64-bit storage. So an "approximate" value may be stored.
+
+For example, these two numbers (right above the safe range) are the same:
+
+```js
+console.log(9007199254740991 + 1); // 9007199254740992
+console.log(9007199254740991 + 2); // 9007199254740992
+```
+
+So to say, all odd integers greater than (253-1) can't be stored at all in the "number" type.
+
+For most purposes ±(253-1) range is quite enough, but sometimes we need the entire range of really big integers, e.g. for cryptography or microsecond-precision timestamps.
+
+`BigInt` type was recently added to the language to represent integers of arbitrary length.
+
+A `BigInt` value is created by appending `n` to the end of an integer:
+
+```js
+// the "n" at the end means it's a BigInt
+const bigInt = 1234567890123456789012345678901234567890n;
+```
+
+As `BigInt` numbers are rarely needed, we don't cover them here, but devoted them a separate chapter . Read it when you need such big numbers.
+
+## String
+
+A string in JavaScript must be surrounded by quotes.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let str = "Hello";
let str2 = 'Single quotes are ok too';
-let phrase = `can embed ${str}`;
+let phrase = `can embed another ${str}`;
```
JavaScriptでは3種類の引用符があります。
@@ -104,7 +182,11 @@ JavaScriptでは3種類の引用符があります。
2. シングルクォート: `'Hello'`.
3. バッククォート: `Hello`.
+<<<<<<< HEAD
ダブル/シングルクォートは "シンプルな" 引用符です。JavaScriptの中ではそれらに違いはありません。
+=======
+Double and single quotes are "simple" quotes. There's practically no difference between them in JavaScript.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
バッククォートは "拡張機能" の引用符です。変数を `${…}` の中にラップすることで、変数を埋め込み文字列の中で表現することができます。たとえば:
@@ -118,15 +200,22 @@ alert( `Hello, *!*${name}*/!*!` ); // Hello, John!
alert( `the result is *!*${1 + 2}*/!*` ); // 結果は 3
```
+<<<<<<< HEAD
`${…}` の中の表現は評価され、結果は文字列の一部になります。そこには何でも置くことができます: `name` のような変数、`1 + 2` のような算術表現、またはより複雑なものを書くこともできます。
これはバッククォートでのみ可能なことに留意してください。他のクォートはこのような埋め込みは許容しません!
+=======
+The expression inside `${…}` is evaluated and the result becomes a part of the string. We can put anything in there: a variable like `name` or an arithmetical expression like `1 + 2` or something more complex.
+
+Please note that this can only be done in backticks. Other quotes don't have this embedding functionality!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( "the result is ${1 + 2}" ); // 結果は ${1 + 2} です(ダブルクォートは何もしません)
```
チャプター で、より深く文字列の説明をします。
+<<<<<<< HEAD
```smart header="*character* 型はありません"
言語によっては、1文字のための特別な "文字" 型があります。たとえば、C言語やJavaでは、それは `char` です。
@@ -134,6 +223,15 @@ JavaScriptではこのような型はありません。`string` 型の1つなだ
```
## boolean (論理型)
+=======
+```smart header="There is no *character* type."
+In some languages, there is a special "character" type for a single character. For example, in the C language and in Java it is called "char".
+
+In JavaScript, there is no such type. There's only one type: `string`. A string may consist of zero characters (be empty), one character or many of them.
+```
+
+## Boolean (logical type)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
boolean 型は2つの値だけを持ちます: `true` と `false`
@@ -154,61 +252,111 @@ let isGreater = 4 > 1;
alert( isGreater ); // true (比較結果は "yes" です)
```
+<<<<<<< HEAD
後ほどチャプターでbooleanのより詳細を説明します。
+=======
+We'll cover booleans more deeply in the chapter .
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## "null" 値
+<<<<<<< HEAD
特殊な `null` 値は上で述べたどの型にも属しません。
それは自身の別の型を形成し、`null` 値だけを含みます。
+=======
+The special `null` value does not belong to any of the types described above.
+
+It forms a separate type of its own which contains only the `null` value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let age = null;
```
+<<<<<<< HEAD
JavaScriptでは、 `null` は他の言語のような "存在しないオブジェクトへの参照" または "null へのポインタ" ではありません。
それは、 "無し"、"空" または "不明な値" と言った意味を持つ特別な値です。
上のコードは、 `age` は何らかの理由で不明な値もしくは空であることを述べています。
+=======
+In JavaScript, `null` is not a "reference to a non-existing object" or a "null pointer" like in some other languages.
+
+It's just a special value which represents "nothing", "empty" or "value unknown".
+
+The code above states that `age` is unknown.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## "undefined" 値
+<<<<<<< HEAD
特殊な値 `undefined` も別に扱われます。`null` のように、それ自身の型を持ちます。
+=======
+The special value `undefined` also stands apart. It makes a type of its own, just like `null`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
`undefined` の意味は "値は代入されていません" です。
+<<<<<<< HEAD
もしも変数は宣言されているが代入されていない場合、その値は正確には `undefined` です:
+=======
+If a variable is declared, but not assigned, then its value is `undefined`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
-let x;
+let age;
+<<<<<<< HEAD
alert(x); // "undefined" を表示
```
技術的にはどの変数にも `undefined` を代入することができます。
+=======
+alert(age); // shows "undefined"
+```
+
+Technically, it is possible to explicitly assign `undefined` to a variable:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = 100;
+<<<<<<< HEAD
// 値を undefined に変更
+=======
+// change the value to undefined
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
age = undefined;
alert(age); // "undefined"
```
+<<<<<<< HEAD
...しかし、そのようにするのは推奨されません。一般的には、 "空" や "不明な値" と言った用途では `null` を使い、`undefined` は変数が割り当てられているか、もしくは似たような確認のために使います。
+=======
+...But we don't recommend doing that. Normally, one uses `null` to assign an "empty" or "unknown" value to a variable, while `undefined` is reserved as a default initial value for unassigned things.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## オブジェクトとシンボル
`object` 型は特殊です。
+<<<<<<< HEAD
他のすべての型は、値は1つのもの(文字列, 数値, または何でも)だけを含むので、"プリミティブ" と呼ばれます。対照的に、オブジェクトはデータのコレクションやより複雑なエンティティを格納するために使われます。
その重要性から、オブジェクトに関してはプリミティブについて詳しく学んだ後に、チャプターで扱います。
+=======
+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.
+
+Being that important, objects deserve a special treatment. 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 the sake of completeness, but also postpone the details till we know objects.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
`symbol` 型はオブジェクトの一意な識別子を作るのに使われます。完全性のためにここで言及していますが、オブジェクトの後で勉強するのがよいでしょう。
+<<<<<<< HEAD
## typeof 演算子
`typeof` 操作は、引数の型を返します。異なる型の値を別々に処理したい、または素早くチェックしたいときに役立ちます。
@@ -221,6 +369,11 @@ alert(age); // "undefined"
言い換えると、それは括弧があってもなくても動作します。結果は同じです。
`typeof x` の呼び出しは型名の文字列を返します。:
+=======
+The `typeof` operator returns the type of the operand. It's useful when we want to process values of different types differently or just want to do a quick check.
+
+A call to `typeof x` returns a string with the type name:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
typeof undefined // "undefined"
@@ -248,6 +401,7 @@ typeof alert // "function" (3)
*/!*
```
+<<<<<<< HEAD
最後の3行については追加の説明が必要かもしれません:
1. `Math` は数学的な操作を提供する組み込みオブジェクトです。チャプターで学ぶでしょう。ここでは、単にオブジェクトとしての例です。
@@ -255,9 +409,27 @@ typeof alert // "function" (3)
3. `alert` は言語の機能なので、`typeof alert` の結果は `"function"` です。我々は次のチャプターで function を勉強します。そして、言語の中には特別な "function" 型がないことがわかるでしょう。function はオブジェクト型に属します。しかし `typeof` はそれらを別々に扱います。正式にはそれは正しくありませんが、実際にはとても便利です。
## サマリ
+=======
+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 an officially recognized error in `typeof`, coming from very early days of JavaScript and kept for compatibility. Definitely, `null` is not an object. It is a special value with a separate type of its own. The behavior of `typeof` is wrong here.
+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 also comes from the early days of JavaScript. Technically, such behavior isn't correct, but can be convenient in practice.
+
+```smart header="The `typeof(x)` syntax"
+You may also come across another syntax: `typeof(x)`. It's the same as `typeof x`.
+
+To put it clear: `typeof` is an operator, not a function. The parentheses here aren't a part of `typeof`. It's the kind of parentheses used for mathematical grouping.
+
+Usually, such parentheses contain a mathematical expression, such as `(2 + 2)`, but here they contain only one argument `(x)`. Syntactically, they allow to avoid a space between the `typeof` operator and its argument, and some people like it.
+
+Some people prefer `typeof(x)`, although the `typeof x` syntax is much more common.
+```
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
JavaScriptには7つの基本型があります。
+<<<<<<< HEAD
- `number` あらゆる種類の数値: 整数または浮動小数点
- `bigint` は任意の長さの整数値のための型
- `string` 文字列。文字列は1つかより多くの文字を持ち、別の1文字型はありません。
@@ -274,3 +446,25 @@ JavaScriptには7つの基本型があります。
- `null` は `"object"` を返します -- それは言語のエラーで、実際はオブジェクトではありません。
次のチャプターではプリミティブ値について集中し、それらに精通した後オブジェクトに進みます。
+=======
+There are 8 basic data types in JavaScript.
+
+- Seven primitive data types:
+ - `number` for numbers of any kind: integer or floating-point, integers are limited by ±(253-1).
+ - `bigint` for integer numbers of arbitrary length.
+ - `string` for strings. A string may have zero or more characters, there's no separate single-character type.
+ - `boolean` for `true`/`false`.
+ - `null` for unknown values -- a standalone type that has a single value `null`.
+ - `undefined` for unassigned values -- a standalone type that has a single value `undefined`.
+ - `symbol` for unique identifiers.
+- And one non-primitive data type:
+ - `object` for more complex data structures.
+
+The `typeof` operator allows us to see which type is stored in a variable.
+
+- Usually used as `typeof x`, but `typeof(x)` is also possible.
+- Returns a string with the name of the type, like `"string"`.
+- For `null` returns `"object"` -- this is an error in the language, it's not actually an object.
+
+In the next chapters, we'll concentrate on primitive values and once we're familiar with them, we'll move on to objects.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/06-alert-prompt-confirm/1-simple-page/task.md b/1-js/02-first-steps/06-alert-prompt-confirm/1-simple-page/task.md
index fc4befa79d..bcea382188 100644
--- a/1-js/02-first-steps/06-alert-prompt-confirm/1-simple-page/task.md
+++ b/1-js/02-first-steps/06-alert-prompt-confirm/1-simple-page/task.md
@@ -2,8 +2,14 @@ importance: 4
---
+<<<<<<< HEAD
# シンプルなページ
名前を訪ねて、それを出力する web ページを作りなさい。
+=======
+# A simple page
+
+Create a web-page that asks for a name and outputs it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
[demo]
diff --git a/1-js/02-first-steps/06-alert-prompt-confirm/article.md b/1-js/02-first-steps/06-alert-prompt-confirm/article.md
index b923845e65..bf43d254d3 100644
--- a/1-js/02-first-steps/06-alert-prompt-confirm/article.md
+++ b/1-js/02-first-steps/06-alert-prompt-confirm/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# インタラクション: alert, prompt, confirm
デモ環境としてブラウザを使っているので、ユーザと対話するためのいくつかの関数を見ておきましょう: `alert`, `prompt` そして `confirm` です
@@ -7,11 +8,23 @@
既にご覧になったと思いますが、メッセージを表示し、ユーザが "OK" をクリックするのを待ちます。
例:
+=======
+# Interaction: alert, prompt, confirm
+
+As we'll be using the browser as our demo environment, let's see a couple of functions to interact with the user: `alert`, `prompt` and `confirm`.
+
+## alert
+
+This one we've seen already. It shows a message and waits for the user to press "OK".
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert("Hello");
```
+<<<<<<< HEAD
メッセージのある小さいウィンドウは *モーダルウィンドウ* と呼ばれます。"モーダル" という言葉は、そのウィンドウを処理するまで(今の場合であれば、OKボタンを押すまで)、訪問者はページの他の部分と対話したり、他のボタンを押すことができないことを意味します。
## prompt
@@ -39,6 +52,35 @@ result = prompt(title[, default]);
`prompt` の呼び出しはフィールドのテキスト、もしくは入力がキャンセルされた場合には `null` が返却されます。
例:
+=======
+The mini-window with the message is called a *modal window*. The word "modal" means that the visitor can't interact with the rest of the page, press other buttons, etc, until they have dealt with the window. In this case -- until they press "OK".
+
+## prompt
+
+The function `prompt` accepts two arguments:
+
+```js no-beautify
+result = prompt(title, [default]);
+```
+
+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.
+
+`default`
+: An optional second parameter, the initial value for the input field.
+
+```smart header="The square brackets in syntax `[...]`"
+The square brackets around `default` in the syntax above denote that the parameter is optional, not required.
+```
+
+The visitor can type something in the prompt input field and press OK. Then we get that text in the `result`. Or they can cancel the input by pressing Cancel or hitting the `key:Esc` key, then we get `null` as the `result`.
+
+The call to `prompt` returns the text from the input field or `null` if the input was canceled.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt('How old are you?', 100);
@@ -46,16 +88,27 @@ let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!
```
+<<<<<<< HEAD
````warn header="IE: 常に `デフォルト` を設定してください"
2つ目のパラメータは任意です。しかし、それを指定しない場合、Internet Explorer はプロンプトにテキスト `"undefined"` を挿入します。
確認する場合、Internet Explorer でこのコードを実行しましょう:
+=======
+````warn header="In IE: always supply a `default`"
+The second parameter is optional, but if we don't supply it, Internet Explorer will insert the text `"undefined"` into the prompt.
+
+Run this code in Internet Explorer to see:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let test = prompt("Test");
```
+<<<<<<< HEAD
なので IEで良く見えるようにするには、常に2つ目の引数を指定することが推奨されます。:
+=======
+So, for prompts to look good in IE, we recommend always providing the second argument:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let test = prompt("Test", ''); // <-- for IE
@@ -64,21 +117,34 @@ let test = prompt("Test", ''); // <-- for IE
## confirm
+<<<<<<< HEAD
構文:
+=======
+The syntax:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
result = confirm(question);
```
+<<<<<<< HEAD
`confirm` 関数は `question` と 2つのボタンをもつモーダルウィンドウを表示します。: OK と キャンセル
OK が押された場合の結果は `true` で、それ以外は `false` です。
例:
+=======
+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.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let isBoss = confirm("Are you the boss?");
+<<<<<<< HEAD
alert( isBoss ); // true OKが押された場合
```
@@ -103,3 +169,29 @@ alert( isBoss ); // true OKが押された場合
2. ウィンドウの正確な見た目もまたブラウザに依存し、それを修正することはできません。
それは単純化に対する代償です。より良いウィンドウを表示し、訪問者とのよりリッチなインタラクションを実現する方法もありますが、"必要以上の装飾" が重要でない場合、これらの方法が使えます。
+=======
+alert( isBoss ); // true if OK is pressed
+```
+
+## Summary
+
+We covered 3 browser-specific functions to interact with visitors:
+
+`alert`
+: shows a message.
+
+`prompt`
+: 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`.
+
+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.
+
+There are two limitations shared by all the methods above:
+
+1. The exact location of the modal window is determined by the browser. Usually, it's in the center.
+2. The exact look of the window also depends on the browser. We can't modify it.
+
+That is the price for simplicity. There are other ways to show nicer windows and richer interaction with the visitor, but if "bells and whistles" do not matter much, these methods work just fine.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/07-type-conversions/article.md b/1-js/02-first-steps/07-type-conversions/article.md
index fcfe4fd090..2a6aaa9cb3 100644
--- a/1-js/02-first-steps/07-type-conversions/article.md
+++ b/1-js/02-first-steps/07-type-conversions/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 型変換
多くの場合、演算子と関数は自動的に値を正しい型に変換します。それを "型変換" と呼びます。
@@ -19,17 +20,45 @@
たとえば、`alert(value)` は値を表示するためにそれを行います。
また、そのために、`String(value)` 関数を使うこともできます:
+=======
+# Type Conversions
+
+Most of the time, operators and functions automatically convert the values given to them to the right type.
+
+For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.
+
+There are also cases when we need to explicitly convert a value to the expected type.
+
+```smart header="Not talking about objects yet"
+In this chapter, we won't cover objects. For now, we'll just be talking about primitives.
+
+Later, after we learn about objects, in the chapter we'll see how objects fit in.
+```
+
+## String Conversion
+
+String conversion happens when we need the string form of a value.
+
+For example, `alert(value)` does it to show the value.
+
+We can also call the `String(value)` function to convert a value to a string:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let value = true;
alert(typeof value); // boolean
*!*
+<<<<<<< HEAD
value = String(value); // 今、値は文字列の "true"
+=======
+value = String(value); // now value is a string "true"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(typeof value); // string
*/!*
```
+<<<<<<< HEAD
文字列変換はほとんどが明白です。`false` は `"false"` に、 `null` は `"null"` になります。
## 数値変換
@@ -43,23 +72,49 @@ alert( "6" / "2" ); // 3, 文字列は数値に変換されます
```
また、明示的に `value` を変換するために `Number(value)` を使うことができます。
+=======
+String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
+
+## Numeric Conversion
+
+Numeric conversion in mathematical functions and expressions happens automatically.
+
+For example, when division `/` is applied to non-numbers:
+
+```js run
+alert( "6" / "2" ); // 3, strings are converted to numbers
+```
+
+We can use the `Number(value)` function to explicitly convert a `value` to a number:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let str = "123";
alert(typeof str); // string
+<<<<<<< HEAD
let num = Number(str); // 数値の 123 になります
+=======
+let num = Number(str); // becomes a number 123
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(typeof num); // number
```
+<<<<<<< HEAD
テキストフォームのような、文字列ベースのソースから値を読むが、数値が入力されることを想定するときには通常明示的な変換が必要になります。
文字列が有効な数値でない場合、このような変換の結果は `NaN` です。たとえば:
+=======
+Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.
+
+If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = Number("an arbitrary string instead of a number");
+<<<<<<< HEAD
alert(age); // NaN, 変換失敗
```
@@ -77,10 +132,30 @@ alert(age); // NaN, 変換失敗
```js run
alert( Number(" 123 ") ); // 123
alert( Number("123z") ); // NaN ("z" の読み込みでエラー)
+=======
+alert(age); // NaN, conversion failed
+```
+
+Numeric conversion rules:
+
+| Value | Becomes... |
+|-------|-------------|
+|`undefined`|`NaN`|
+|`null`|`0`|
+|true and false | `1` and `0` |
+| `string` | Whitespaces (includes spaces, tabs `\t`, newlines `\n` etc.) from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. |
+
+Examples:
+
+```js run
+alert( Number(" 123 ") ); // 123
+alert( Number("123z") ); // NaN (error reading a number at "z")
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( Number(true) ); // 1
alert( Number(false) ); // 0
```
+<<<<<<< HEAD
`null` と `undefined` はここでは異なる振る舞いをすることに留意してください。: `undefined` が `NaN` になる一方、`null` は 0 になります。
ほとんどの算術演算もこのような変換を行います。次のチャプターでそれらを詳しく見ていきます。
@@ -97,6 +172,24 @@ alert( Number(false) ); // 0
- 他の値は `true` になります。
例:
+=======
+Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
+
+Most mathematical operators also perform such conversion, we'll see that in the next chapter.
+
+## Boolean Conversion
+
+Boolean conversion is the simplest one.
+
+It happens in logical operations (later we'll meet condition tests and other similar things) but can also be performed explicitly with a call to `Boolean(value)`.
+
+The conversion rule:
+
+- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
+- Other values become `true`.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( Boolean(1) ); // true
@@ -106,6 +199,7 @@ alert( Boolean("hello") ); // true
alert( Boolean("") ); // false
```
+<<<<<<< HEAD
````warn header="注意してください: ゼロの文字列 `\"0\"` は `true` です"
幾つかの言語(すなわち PHP)は `”0”` を `false` として扱います。しかし、JavaScriptでは、非空文字は常に `true` です。
@@ -148,3 +242,47 @@ alert( Boolean(" ") ); // スペースもまた true です (任意の非空文
- `"0"` と `" "` のようなスペースだけの文字列は真偽値としては true です。
オブジェクトについてはここでは説明しませんが、JavaScriptについての基本的なことを学んだら、オブジェクトに専念する の章の後半に戻ります。
+=======
+````warn header="Please note: the string with zero `\"0\"` is `true`"
+Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`.
+
+```js run
+alert( Boolean("0") ); // true
+alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
+```
+````
+
+## Summary
+
+The three most widely used type conversions are to string, to number, and to boolean.
+
+**`String Conversion`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
+
+**`Numeric Conversion`** -- Occurs in math operations. Can be performed with `Number(value)`.
+
+The conversion follows the rules:
+
+| Value | Becomes... |
+|-------|-------------|
+|`undefined`|`NaN`|
+|`null`|`0`|
+|true / false | `1 / 0` |
+| `string` | The string is read "as is", whitespaces (includes spaces, tabs `\t`, newlines `\n` etc.) from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
+
+**`Boolean Conversion`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
+
+Follows the rules:
+
+| Value | Becomes... |
+|-------|-------------|
+|`0`, `null`, `undefined`, `NaN`, `""` |`false`|
+|any other value| `true` |
+
+
+Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:
+
+- `undefined` is `NaN` as a number, not `0`.
+- `"0"` and space-only strings like `" "` are true as a boolean.
+
+Objects aren't covered here. We'll return to them later in the chapter that is devoted exclusively to objects after we learn more basic things about JavaScript.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/1-increment-order/solution.md b/1-js/02-first-steps/08-operators/1-increment-order/solution.md
index cd510145ac..2216e27878 100644
--- a/1-js/02-first-steps/08-operators/1-increment-order/solution.md
+++ b/1-js/02-first-steps/08-operators/1-increment-order/solution.md
@@ -1,5 +1,9 @@
+<<<<<<< HEAD
答えは次の通りです:
+=======
+The answer is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- `a = 2`
- `b = 2`
@@ -9,9 +13,19 @@
```js run no-beautify
let a = 1, b = 1;
+<<<<<<< HEAD
alert( ++a ); // 2, 前置式は新しい値を返します
alert( b++ ); // 1, 後置式は古い値を返します
alert( a ); // 2, 1回インクリメントされています
alert( b ); // 2, 1回インクリメントされています
```
+=======
+alert( ++a ); // 2, prefix form returns the new value
+alert( b++ ); // 1, postfix form returns the old value
+
+alert( a ); // 2, incremented once
+alert( b ); // 2, incremented once
+```
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/1-increment-order/task.md b/1-js/02-first-steps/08-operators/1-increment-order/task.md
index 9c07e5f7ef..9e140ee08e 100644
--- a/1-js/02-first-steps/08-operators/1-increment-order/task.md
+++ b/1-js/02-first-steps/08-operators/1-increment-order/task.md
@@ -2,9 +2,15 @@ importance: 5
---
+<<<<<<< HEAD
# プレフィックス(接頭辞)とサフィックス(接尾辞)の形式
下のコードが実行されたあと、変数 `a`, `b`, `c`, `d` はいくつになるでしょう?
+=======
+# The postfix and prefix forms
+
+What are the final values of all variables `a`, `b`, `c` and `d` after the code below?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let a = 1, b = 1;
diff --git a/1-js/02-first-steps/08-operators/2-assignment-result/solution.md b/1-js/02-first-steps/08-operators/2-assignment-result/solution.md
index d9c3d96683..5280fe2310 100644
--- a/1-js/02-first-steps/08-operators/2-assignment-result/solution.md
+++ b/1-js/02-first-steps/08-operators/2-assignment-result/solution.md
@@ -1,4 +1,12 @@
+<<<<<<< HEAD
答えは次の通りです:
- `a = 4` (2で掛けられています)
- `x = 5` (1 + 4 と計算されます)
+=======
+The answer is:
+
+- `a = 4` (multiplied by 2)
+- `x = 5` (calculated as 1 + 4)
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/2-assignment-result/task.md b/1-js/02-first-steps/08-operators/2-assignment-result/task.md
index 4b6db6a9e1..a6e7320c94 100644
--- a/1-js/02-first-steps/08-operators/2-assignment-result/task.md
+++ b/1-js/02-first-steps/08-operators/2-assignment-result/task.md
@@ -2,9 +2,15 @@ importance: 3
---
+<<<<<<< HEAD
# 代入の結果
下のコードが実行されたあと、`a` と `x` はいくつになるでしょう?
+=======
+# Assignment result
+
+What are the values of `a` and `x` after the code below?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let a = 2;
diff --git a/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/solution.md b/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/solution.md
index d3e7ee2e8a..69cb2323c1 100644
--- a/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/solution.md
+++ b/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/solution.md
@@ -9,14 +9,20 @@ true + false = 1
"$" + 4 + 5 = "$45"
"4" - 2 = 2
"4px" - 2 = NaN
+<<<<<<< HEAD
7 / 0 = Infinity
" -9 " + 5 = " -9 5" // (3)
" -9 " - 5 = -14 // (4)
+=======
+" -9 " + 5 = " -9 5" // (3)
+" -9 " - 5 = -14 // (4)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
null + 1 = 1 // (5)
undefined + 1 = NaN // (6)
" \t \n" - 2 = -2 // (7)
```
+<<<<<<< HEAD
1. 文字列の追加 `"" + 1` では `1` を文字列に変換します: `"" + 1 = "1"`, そして `"1" + 0` には同じルールが適用されます。
2. 減算 `-` (ほとんどの算術演算子と同様)は数値でのみ動作し、空の文字列 `""` を `0` に変換します
3. 文字列の追加は、数値 `5` を文字列に追加します。
@@ -24,3 +30,12 @@ undefined + 1 = NaN // (6)
5. `null` は数値変換後は `0` になります。
6. `undefined` は数値変換後は `NaN` になります。
7. 文字列の先頭/末尾のスペースは、文字列が数値に変換される際に削除されます。ここでは文字列全体が `\t` や `\n`、"通常" のスペース文字から構成されています。したがって、空文字列のときと同様、`0` になります。
+=======
+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.
+2. The subtraction `-` (like most math operations) only works with numbers, it converts an empty string `""` to `0`.
+3. The addition with a string appends the number `5` to the string.
+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`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/task.md b/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/task.md
index 4d25a1f207..f62050a847 100644
--- a/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/task.md
+++ b/1-js/02-first-steps/08-operators/3-primitive-conversions-questions/task.md
@@ -2,9 +2,15 @@ importance: 5
---
+<<<<<<< HEAD
# 型変換
これらの式の結果はどうなるでしょう?
+=======
+# Type conversions
+
+What are results of these expressions?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
"" + 1 + 0
@@ -16,7 +22,10 @@ true + false
"$" + 4 + 5
"4" - 2
"4px" - 2
+<<<<<<< HEAD
7 / 0
+=======
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
" -9 " + 5
" -9 " - 5
null + 1
@@ -24,4 +33,8 @@ undefined + 1
" \t \n" - 2
```
+<<<<<<< HEAD
よく考え、書き留めてから答えあわせしてみてください。
+=======
+Think well, write down and then compare with the answer.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/4-fix-prompt/solution.md b/1-js/02-first-steps/08-operators/4-fix-prompt/solution.md
index 32cc581eaf..13750096ef 100644
--- a/1-js/02-first-steps/08-operators/4-fix-prompt/solution.md
+++ b/1-js/02-first-steps/08-operators/4-fix-prompt/solution.md
@@ -1,6 +1,12 @@
+<<<<<<< HEAD
理由はプロンプトがユーザ入力を文字列として返すからです。
なので、変数はそれぞれ値 `"1"` と `"2"` になります。
+=======
+The reason is that prompt returns user input as a string.
+
+So variables have values `"1"` and `"2"` respectively.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = "1"; // prompt("First number?", 1);
@@ -9,9 +15,15 @@ let b = "2"; // prompt("Second number?", 2);
alert(a + b); // 12
```
+<<<<<<< HEAD
すべきことは、`+` の前に、文字列から数値へ変換することです。例えば、`Number()` を使用したり、それらの前に `+` をつけます。
例えば、。`prompt` の直前:
+=======
+What we should do is to convert strings to numbers before `+`. For example, using `Number()` or prepending them with `+`.
+
+For example, right before `prompt`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = +prompt("First number?", 1);
@@ -20,7 +32,11 @@ let b = +prompt("Second number?", 2);
alert(a + b); // 3
```
+<<<<<<< HEAD
あるいは `alert`:
+=======
+Or in the `alert`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = prompt("First number?", 1);
@@ -29,4 +45,8 @@ let b = prompt("Second number?", 2);
alert(+a + +b); // 3
```
+<<<<<<< HEAD
最新のコードでは、単項と二項の `+` 両方を使用しています。面白いですね。
+=======
+Using both unary and binary `+` in the latest code. Looks funny, doesn't it?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/08-operators/4-fix-prompt/task.md b/1-js/02-first-steps/08-operators/4-fix-prompt/task.md
index 7809de4545..6d3ee0a63d 100644
--- a/1-js/02-first-steps/08-operators/4-fix-prompt/task.md
+++ b/1-js/02-first-steps/08-operators/4-fix-prompt/task.md
@@ -2,6 +2,7 @@ importance: 5
---
+<<<<<<< HEAD
# 足し算を修正する
ユーザに2つの数字を訪ね、その合計を表示するコードがあります。
@@ -9,6 +10,15 @@ importance: 5
これは正しく機能していません。以下の例の出力は `12` です(デフォルトのプロンプトの値の場合)。
なぜでしょうか?修正してください。結果は `3` になるべきです。
+=======
+# Fix the addition
+
+Here's a code that asks the user for two numbers and shows their sum.
+
+It works incorrectly. The output in the example below is `12` (for default prompt values).
+
+Why? Fix it. The result should be `3`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = prompt("First number?", 1);
diff --git a/1-js/02-first-steps/08-operators/article.md b/1-js/02-first-steps/08-operators/article.md
index 4b4a8fbaab..0863486acb 100644
--- a/1-js/02-first-steps/08-operators/article.md
+++ b/1-js/02-first-steps/08-operators/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 演算子
多くの演算子は既に学校で学んでおり、よく知られています。加算 `+`, 乗算 `*`, 減算 `-` などです。
@@ -10,6 +11,20 @@
- *オペランド* -- は演算子が適用されるものです。たとえば、 乗算 `5 * 2` では、2つのオペランドがあります: 左のオペランドは `5`, 右のオペランドは `2` です。"オペランド" は "引数" と呼ばれることもあります。
- 演算子が単一のオペランドをもつ場合は *単項演算* です。たとえば、負の単項演算 `"-"` は数値の符号を反転します:
+=======
+# Basic operators, maths
+
+We know many operators from school. They are things like addition `+`, multiplication `*`, subtraction `-`, and so on.
+
+In this chapter, we’ll start with simple operators, then concentrate on JavaScript-specific aspects, not covered by school arithmetic.
+
+## Terms: "unary", "binary", "operand"
+
+Before we move on, let's grasp some common terminology.
+
+- *An operand* -- is what operators are applied to. For instance, in the multiplication of `5 * 2` there are two operands: the left operand is `5` and the right operand is `2`. Sometimes, people call these "arguments" instead of "operands".
+- An operator is *unary* if it has a single operand. For example, the unary negation `-` reverses the sign of a number:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let x = 1;
@@ -17,6 +32,7 @@
*!*
x = -x;
*/!*
+<<<<<<< HEAD
alert( x ); // -1, 負の単項演算が適用されました
```
- 演算子が2つのオペランドを持つ場合は *二項演算* です。同じマイナスも二項演算で同様に存在します:
@@ -81,21 +97,99 @@ alert( 8 ** (1/3) ); // 2 (1/3 の累乗は立方根と同じです)
通常、プラス演算子 `+` は数値の合計です。
しかし二項演算子 `+` が文字列に適用された場合は、お互いの文字を結合します。
+=======
+ alert( x ); // -1, unary negation was applied
+ ```
+- An operator is *binary* if it has two operands. The same minus exists in binary form as well:
+
+ ```js run no-beautify
+ let x = 1, y = 3;
+ alert( y - x ); // 2, binary minus subtracts values
+ ```
+
+ 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.
+
+## Maths
+
+The following math operations are supported:
+
+- Addition `+`,
+- Subtraction `-`,
+- Multiplication `*`,
+- Division `/`,
+- Remainder `%`,
+- Exponentiation `**`.
+
+The first four are straightforward, while `%` and `**` need a few words about them.
+
+### Remainder %
+
+The remainder operator `%`, despite its appearance, is not related to percents.
+
+The result of `a % b` is the [remainder](https://en.wikipedia.org/wiki/Remainder) of the integer division of `a` by `b`.
+
+For instance:
+
+```js run
+alert( 5 % 2 ); // 1, the remainder of 5 divided by 2
+alert( 8 % 3 ); // 2, the remainder of 8 divided by 3
+alert( 8 % 4 ); // 0, the remainder of 8 divided by 4
+```
+
+### Exponentiation **
+
+The exponentiation operator `a ** b` raises `a` to the power of `b`.
+
+In school maths, we write that as ab.
+
+For instance:
+
+```js run
+alert( 2 ** 2 ); // 2² = 4
+alert( 2 ** 3 ); // 2³ = 8
+alert( 2 ** 4 ); // 2⁴ = 16
+```
+
+Just like in maths, the exponentiation operator is defined for non-integer numbers as well.
+
+For example, a square root is an exponentiation by ½:
+
+```js run
+alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
+alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
+```
+
+
+## String concatenation with binary +
+
+Let's meet the features of JavaScript operators that are beyond school arithmetics.
+
+Usually, the plus operator `+` sums numbers.
+
+But, if the binary `+` is applied to strings, it merges (concatenates) them:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let s = "my" + "string";
alert(s); // mystring
```
+<<<<<<< HEAD
一方のオペランドが文字列の場合、他のオペランドも文字列に変換されることに注意してください。
例:
+=======
+Note that if any of the operands is a string, then the other one is converted to a string too.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
```
+<<<<<<< HEAD
ご覧の通り、どちらのオペランドが文字列なのかは関係ありません。
こちらはより複雑な例です:
@@ -130,6 +224,42 @@ alert( '6' / '2' ); // 3, 両方のオペランドを数値に変換します
```js run
// 数値の場合、何の影響もありません
+=======
+See, it doesn't matter whether the first operand is a string or the second one.
+
+Here's a more complex example:
+
+```js run
+alert(2 + 2 + '1' ); // "41" and not "221"
+```
+
+Here, operators work one after another. The first `+` sums two numbers, so it returns `4`, then the next `+` adds the string `1` to it, so it's like `4 + '1' = '41'`.
+
+```js run
+alert('1' + 2 + 2); // "122" and not "14"
+```
+Here, the first operand is a string, the compiler treats the other two operands as strings too. The `2` gets concatenated to `'1'`, so it's like `'1' + 2 = "12"` and `"12" + 2 = "122"`.
+
+The binary `+` is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.
+
+Here's the demo for subtraction and division:
+
+```js run
+alert( 6 - '2' ); // 4, converts '2' to a number
+alert( '6' / '2' ); // 3, converts both operands to numbers
+```
+
+## Numeric conversion, unary +
+
+The plus `+` exists in two forms: the binary form that we used above and the unary form.
+
+The unary plus or, in other words, the plus operator `+` applied to a single value, doesn't do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.
+
+For example:
+
+```js run
+// No effect on numbers
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let x = 1;
alert( +x ); // 1
@@ -137,32 +267,52 @@ let y = -2;
alert( +y ); // -2
*!*
+<<<<<<< HEAD
// 非数値を数値に変換します
+=======
+// Converts non-numbers
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( +true ); // 1
alert( +"" ); // 0
*/!*
```
+<<<<<<< HEAD
これは `Number(...)` と同じですが、より短い表現です。
文字列から数値への変換が必要なケースは多いです。例えば、HTMLのフォームフィールドから値を取得する場合、それらは通常文字列です。今、それらの合計が欲しい場合はどうなるでしょう?
二項演算子プラスはそれらを文字列として結合します。:
+=======
+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 binary plus would add them as strings:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let apples = "2";
let oranges = "3";
+<<<<<<< HEAD
alert( apples + oranges ); // "23", 二項演算子プラスは文字列を結合します
```
数値として扱いたい場合は変換して合計します:
+=======
+alert( apples + oranges ); // "23", the binary plus concatenates strings
+```
+
+If we want to treat them as numbers, we need to convert and then sum them:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let apples = "2";
let oranges = "3";
*!*
+<<<<<<< HEAD
// 二項演算子プラスの処理の前に、両方の値が数値に変換されます
alert( +apples + +oranges ); // 5
*/!*
@@ -208,6 +358,53 @@ JavaScriptでは多くの演算子があります。どの演算子も対応す
代入 `=` もまた演算子であることに注意しましょう。 `2`というとても低い値として優先順位の一覧に並んでいます。
なので `x = 2 * 2 + 1` のように変数に代入するとき、計算が最初に行われ、その後 `=` が評価され、 `x` に結果が格納されます。
+=======
+// both values converted to numbers before the binary plus
+alert( +apples + +oranges ); // 5
+*/!*
+
+// the longer variant
+// alert( Number(apples) + Number(oranges) ); // 5
+```
+
+From a mathematician's standpoint, the abundance of pluses may seem strange. But from a programmer's standpoint, there's nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.
+
+Why are unary pluses applied to values before the binary ones? As we're going to see, that's because of their *higher precedence*.
+
+## Operator precedence
+
+If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, the default priority order of operators.
+
+From school, we all know that the multiplication in the expression `1 + 2 * 2` should be calculated before the addition. That's exactly the precedence thing. The multiplication is said to have *a higher precedence* than the addition.
+
+Parentheses override any precedence, so if we're not satisfied with the default order, we can use them to change it. For example, write `(1 + 2) * 2`.
+
+There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the larger number executes first. If the precedence is the same, the execution order is from left to right.
+
+Here's an extract from the [precedence table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) (you don't need to remember this, but note that unary operators are higher than corresponding binary ones):
+
+| Precedence | Name | Sign |
+|------------|------|------|
+| ... | ... | ... |
+| 14 | unary plus | `+` |
+| 14 | unary negation | `-` |
+| 13 | exponentiation | `**` |
+| 12 | multiplication | `*` |
+| 12 | division | `/` |
+| 11 | addition | `+` |
+| 11 | subtraction | `-` |
+| ... | ... | ... |
+| 2 | assignment | `=` |
+| ... | ... | ... |
+
+As we can see, the "unary plus" has a priority of `14` which is higher than the `11` of "addition" (binary plus). That's why, in the expression `"+apples + +oranges"`, unary pluses work before the addition.
+
+## Assignment
+
+Let's note that an assignment `=` is also an operator. It is listed in the precedence table with the very low priority of `2`.
+
+That's why, when we assign a variable, like `x = 2 * 2 + 1`, the calculations are done first and then the `=` is evaluated, storing the result in `x`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let x = 2 * 2 + 1;
@@ -215,6 +412,7 @@ let x = 2 * 2 + 1;
alert( x ); // 5
```
+<<<<<<< HEAD
### 代入 = は値を返します
`=` が演算子であり、"魔法の" 言語構造でないという事実は、興味深い意味合いを持っています。
@@ -224,6 +422,17 @@ JavaScript のすべての演算子は値を返却します。これは `+` や
`x = value` の呼び出しでは、`value` を `x` に書き込み、*その値を返却します。*
これは、複雑な式の一部に代入を使用した例です:
+=======
+### Assignment = returns a value
+
+The fact of `=` being an operator, not a "magical" language construct has an interesting implication.
+
+All operators in JavaScript return a value. That's obvious for `+` and `-`, but also true for `=`.
+
+The call `x = value` writes the `value` into `x` *and then returns it*.
+
+Here's a demo that uses an assignment as part of a more complex expression:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = 1;
@@ -237,6 +446,7 @@ alert( a ); // 3
alert( c ); // 0
```
+<<<<<<< HEAD
上記の例では、式 `(a = b + 1)` の結果は `a` に代入された値(つまり `3`)です。その後、以降の評価で利用されています。
面白いですよね? JavaScript ライブラリで時々目にするので、これがどのように動くのかは理解しておく必要があります。
@@ -246,6 +456,17 @@ alert( c ); // 0
# 代入のチェーン
もう1つの興味深い特徴は、代入をチェーンする機能です:
+=======
+In the example above, the result of expression `(a = b + 1)` is the value which was assigned to `a` (that is `3`). It is then used for further evaluations.
+
+Funny code, isn't it? We should understand how it works, because sometimes we see it in JavaScript libraries.
+
+Although, please don't write the code like that. Such tricks definitely don't make code clearer or readable.
+
+### Chaining assignments
+
+Another interesting feature is the ability to chain assignments:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a, b, c;
@@ -259,15 +480,22 @@ alert( b ); // 4
alert( c ); // 4
```
+<<<<<<< HEAD
チェーンされた代入は右から左へ評価されます。最初に最も右の式 `2 + 2` が評価され、次に左の変数に代入されます。: `c`, `b` と `a`です。最後にすべての変数は単一の値になります。
改めて言いますが、可読性を上げるためには、このようなコードを複数行に分割する方がよいです:
+=======
+Chained assignments evaluate from right to left. First, the rightmost expression `2 + 2` is evaluated and then assigned to the variables on the left: `c`, `b` and `a`. At the end, all the variables share a single value.
+
+Once again, for the purposes of readability it's better to split such code into few lines:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
c = 2 + 2;
b = c;
a = c;
```
+<<<<<<< HEAD
これは読みやすいですね。コードを素早く眺めているときには特に。
## インプレース(in-place)修正
@@ -275,6 +503,15 @@ a = c;
変数に演算子を適用したあと、新しい結果を同じ変数に格納したいことは頻繁にあります。
例:
+=======
+That's easier to read, especially when eye-scanning the code fast.
+
+## Modify-in-place
+
+We often need to apply an operator to a variable and store the new result in that same variable.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let n = 2;
@@ -282,23 +519,39 @@ n = n + 5;
n = n * 2;
```
+<<<<<<< HEAD
この表記は演算子 `+=` や `*=` を使用して短縮することができます:
```js run
let n = 2;
n += 5; // n = 7 (n = n + 5 と同じ)
n *= 2; // n = 14 (n = n * 2 と同じ)
+=======
+This notation can be shortened using the operators `+=` and `*=`:
+
+```js run
+let n = 2;
+n += 5; // now n = 7 (same as n = n + 5)
+n *= 2; // now n = 14 (same as n = n * 2)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( n ); // 14
```
+<<<<<<< HEAD
短縮の "変更と代入" 演算子はすべての算術演算とビット演算子に存在します: `/=`, `-=` 等
このような演算子は通常の代入と同じ優先順位になります。なので、他のほとんどの計算の後に実行されます:
+=======
+Short "modify-and-assign" operators exist for all arithmetical and bitwise operators: `/=`, `-=`, etc.
+
+Such operators have the same precedence as a normal assignment, so they run after most other calculations:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let n = 2;
+<<<<<<< HEAD
n *= 3 + 5;
alert( n ); // 16 (最初に右辺が評価されるので n *= 8 と同じです)
@@ -324,10 +577,38 @@ alert( n ); // 16 (最初に右辺が評価されるので n *= 8 と同じ
```js run no-beautify
let counter = 2;
counter--; // counter = counter - 1 と同じですがより短いです
+=======
+n *= 3 + 5; // right part evaluated first, same as n *= 8
+
+alert( n ); // 16
+```
+
+## Increment/decrement
+
+
+
+Increasing or decreasing a number by one is among the most common numerical operations.
+
+So, there are special operators for it:
+
+- **Increment** `++` increases a variable by 1:
+
+ ```js run no-beautify
+ let counter = 2;
+ 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
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( counter ); // 1
```
```warn
+<<<<<<< HEAD
インクリメント/デクリメントは変数に対してのみ適用可能です。 それを `5++` のように値に対して使おうとするとエラーになります。
```
@@ -343,6 +624,23 @@ alert( n ); // 16 (最初に右辺が評価されるので n *= 8 と同じ
違いを明確にしましょう。ご存知の通り、すべての演算子は値を返します。インクリメント/デクリメントも例外ではありません。前置式は新しい値を返す一方、後置式は古い値を返します(インクリメント/デクリメントの前)。
違いを例で見てみましょう。
+=======
+Increment/decrement can only be applied to variables. Trying to use it on a value like `5++` will give an error.
+```
+
+The operators `++` and `--` can be placed either before or after a variable.
+
+- When the operator goes after the variable, it is in "postfix form": `counter++`.
+- The "prefix form" is when the operator goes before the variable: `++counter`.
+
+Both of these statements do the same thing: increase `counter` by `1`.
+
+Is there any difference? Yes, but we can only see it if we use the returned value of `++/--`.
+
+Let's clarify. As we know, all operators return a value. Increment/decrement is no exception. The prefix form returns the new value while the postfix form returns the old value (prior to increment/decrement).
+
+To see the difference, here's an example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 1;
@@ -351,6 +649,7 @@ let a = ++counter; // (*)
alert(a); // *!*2*/!*
```
+<<<<<<< HEAD
ここで `(*)` の行の前置呼び出し `++counter` は `counter` を増加させ、`2` という新しい値を返します。そのため、 `alert` は `2` を表示します。
後置式を使いましょう:
@@ -358,45 +657,80 @@ alert(a); // *!*2*/!*
```js run
let counter = 1;
let a = counter++; // (*) ++counter を counter++ に変更
+=======
+In the line `(*)`, the *prefix* form `++counter` increments `counter` and returns the new value, `2`. So, the `alert` shows `2`.
+
+Now, let's use the postfix form:
+
+```js run
+let counter = 1;
+let a = counter++; // (*) changed ++counter to counter++
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(a); // *!*1*/!*
```
+<<<<<<< HEAD
`(*)` の行で、 *後置* 式 `counter++` は `counter` を増加させますが、 *古い* 値を返します(増加する前)。そのため、 `alert` は `1` を表示します。
要約すると:
- インクリメント/デクリメントの結果を使わない場合、どちらの形式を使っても違いはありません。:
+=======
+In the line `(*)`, the *postfix* form `counter++` also increments `counter` but returns the *old* value (prior to increment). So, the `alert` shows `1`.
+
+To summarize:
+
+- If the result of increment/decrement is not used, there is no difference in which form to use:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 0;
counter++;
++counter;
+<<<<<<< HEAD
alert( counter ); // 2, 上の行は同じことをします
```
- 値の増加に *加えて*、すぐに演算子の結果を使いたい場合は前置式が必要になります:
+=======
+ alert( counter ); // 2, the lines above did the same
+ ```
+- If we'd like to increase a value *and* immediately use the result of the operator, we need the prefix form:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 0;
alert( ++counter ); // 1
```
+<<<<<<< HEAD
- 増加させるが、以前の値を使いたい場合は後置式が必要です:
+=======
+- If we'd like to increment a value but use its previous value, we need the postfix form:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 0;
alert( counter++ ); // 0
```
+<<<<<<< HEAD
````smart header="他の演算子の中でのインクリメント/デクリメント"
演算子 `++/--` は同様に式の中でも使うことができます。それらの優先順位は他の算術演算子よりも高いです。
例:
+=======
+````smart header="Increment/decrement among other operators"
+The operators `++/--` can be used inside expressions as well. Their precedence is higher than most other arithmetical operations.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 1;
alert( 2 * ++counter ); // 4
```
+<<<<<<< HEAD
比較:
```js run
@@ -409,6 +743,20 @@ alert( 2 * counter++ ); // 2, counter++ は "古い" 値を返すからです
コードを読むとき、上から読んでいく "縦の" 目視はこのような `counter++` を見逃しやすく、また変数の増加が明白ではありません。
"1行は1アクション" のスタイルが推奨されます:
+=======
+Compare with:
+
+```js run
+let counter = 1;
+alert( 2 * counter++ ); // 2, because counter++ returns the "old" value
+```
+
+Though technically okay, such notation usually makes code less readable. One line does multiple things -- not good.
+
+While reading code, a fast "vertical" eye-scan can easily miss something like `counter++` and it won't be obvious that the variable increased.
+
+We advise a style of "one line -- one action":
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let counter = 1;
@@ -417,6 +765,7 @@ counter++;
```
````
+<<<<<<< HEAD
## ビット演算子
ビット演算子は引数を 32ビットの整数値として扱い、それらのバイナリ表現のレベルで処理します。
@@ -424,6 +773,15 @@ counter++;
これらの演算子はJavaScript固有のものではありません。多くのプログラミング言語でサポートされています。
演算子のリスト:
+=======
+## Bitwise operators
+
+Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary representation.
+
+These operators are not JavaScript-specific. They are supported in most programming languages.
+
+The list of operators:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- AND ( `&` )
- OR ( `|` )
@@ -433,6 +791,7 @@ counter++;
- RIGHT SHIFT ( `>>` )
- ZERO-FILL RIGHT SHIFT ( `>>>` )
+<<<<<<< HEAD
これらの演算子はめったに使われません。それらを理解するためには、低レベルの数値表現について掘り下げるべきであり、それは現時点では最適ではないでしょう。すぐには必要ないからです。もし興味がある場合は、MDNの[ビット演算子 ](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators#binary_bitwise_operators)の記事を参照してください。実際に必要になったときにそれをするのが現実的でしょう。
## カンマ
@@ -442,12 +801,24 @@ counter++;
カンマ演算子を使うと複数の式を評価できます。それらの式はカンマ `','` で区切られています。それぞれが評価されますが、最後の結果のみが返却されます。
例:
+=======
+These operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level. We won't need these operators any time soon, as web development has little use of them, but in some special areas, such as cryptography, they are useful. You can read the [Bitwise Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators) chapter on MDN when a need arises.
+
+## Comma
+
+The comma operator `,` is one of the rarest and most unusual operators. Sometimes, it's used to write shorter code, so we need to know it in order to understand what's going on.
+
+The comma operator allows us to evaluate several expressions, dividing them with a comma `,`. Each of them is evaluated but only the result of the last one is returned.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
let a = (1 + 2, 3 + 4);
*/!*
+<<<<<<< HEAD
alert( a ); // 7 (3 + 4 の結果)
```
@@ -467,9 +838,34 @@ alert( a ); // 7 (3 + 4 の結果)
```js
// 1行に3つの演算子
+=======
+alert( a ); // 7 (the result of 3 + 4)
+```
+
+Here, the first expression `1 + 2` is evaluated and its result is thrown away. Then, `3 + 4` is evaluated and returned as the result.
+
+```smart header="Comma has a very low precedence"
+Please note that the comma operator has very low precedence, lower than `=`, so parentheses are important in the example above.
+
+Without them: `a = 1 + 2, 3 + 4` evaluates `+` first, summing the numbers into `a = 3, 7`, then the assignment operator `=` assigns `a = 3`, and the rest is ignored. It's like `(a = 1 + 2), 3 + 4`.
+```
+
+Why do we need an operator that throws away everything except the last expression?
+
+Sometimes, people use it in more complex constructs to put several actions in one line.
+
+For example:
+
+```js
+// three operations in one line
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) {
...
}
```
+<<<<<<< HEAD
このようなトリックは多くのJavaScriptフレームワークで利用されているため、ここで言及しています。しかし通常それらはコードの可読性を下げます。なので、そのように書く前によく考えるべきです。
+=======
+Such tricks are used in many JavaScript frameworks. That's why we're mentioning them. But usually they don't improve code readability so we should think well before using them.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/09-comparison/1-comparison-questions/solution.md b/1-js/02-first-steps/09-comparison/1-comparison-questions/solution.md
index de42c992a0..e4cadcac7b 100644
--- a/1-js/02-first-steps/09-comparison/1-comparison-questions/solution.md
+++ b/1-js/02-first-steps/09-comparison/1-comparison-questions/solution.md
@@ -10,6 +10,7 @@ null == "\n0\n" → false
null === +"\n0\n" → false
```
+<<<<<<< HEAD
理由:
1. 明らかに true ですね。
@@ -19,3 +20,14 @@ null === +"\n0\n" → false
5. 厳密等価は厳密です。両側が異なる型だと false になります。
6. (4) をみてください。
7. 異なる型の厳密等価です。
+=======
+Some of the reasons:
+
+1. Obviously, true.
+2. Dictionary comparison, hence false. `"a"` is smaller than `"p"`.
+3. Again, dictionary comparison, first char `"2"` is greater than the first char `"1"`.
+4. Values `null` and `undefined` equal each other only.
+5. Strict equality is strict. Different types from both sides lead to false.
+6. Similar to `(4)`, `null` only equals `undefined`.
+7. Strict equality of different types.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/09-comparison/1-comparison-questions/task.md b/1-js/02-first-steps/09-comparison/1-comparison-questions/task.md
index c1153f6323..83178aebcf 100644
--- a/1-js/02-first-steps/09-comparison/1-comparison-questions/task.md
+++ b/1-js/02-first-steps/09-comparison/1-comparison-questions/task.md
@@ -4,7 +4,11 @@ importance: 5
# 比較
+<<<<<<< HEAD
式の結果はどうなるでしょう?
+=======
+What will be the result for these expressions?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
5 > 4
diff --git a/1-js/02-first-steps/09-comparison/article.md b/1-js/02-first-steps/09-comparison/article.md
index 7d73111424..1dc44e46ff 100644
--- a/1-js/02-first-steps/09-comparison/article.md
+++ b/1-js/02-first-steps/09-comparison/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 比較
私たちは数学にある多くの比較演算子を知っています。:
@@ -42,6 +43,52 @@ alert( result ); // true
言い換えると、文字列は文字単位で比較されます。
例:
+=======
+# Comparisons
+
+We know many comparison operators from maths.
+
+In JavaScript they are written like this:
+
+- Greater/less than: a > b, a < b.
+- Greater/less than or equals: a >= b, a <= b.
+- Equals: `a == b`, please note the double equality sign `==` means the equality test, while a single one `a = b` means an assignment.
+- Not equals: In maths the notation is ≠, but in JavaScript it's written as a != b.
+
+In this article we'll learn more about different types of comparisons, how JavaScript makes them, including important peculiarities.
+
+At the end you'll find a good recipe to avoid "JavaScript quirks"-related issues.
+
+## Boolean is the result
+
+All comparison operators return a boolean value:
+
+- `true` -- means "yes", "correct" or "the truth".
+- `false` -- means "no", "wrong" or "not the truth".
+
+For example:
+
+```js run
+alert( 2 > 1 ); // true (correct)
+alert( 2 == 1 ); // false (wrong)
+alert( 2 != 1 ); // true (correct)
+```
+
+A comparison result can be assigned to a variable, just like any value:
+
+```js run
+let result = 5 > 4; // assign the result of the comparison
+alert( result ); // true
+```
+
+## String comparison
+
+To see whether a string is greater than another, JavaScript uses the so-called "dictionary" or "lexicographical" order.
+
+In other words, strings are compared letter-by-letter.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( 'Z' > 'A' ); // true
@@ -49,6 +96,7 @@ alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true
```
+<<<<<<< HEAD
2つの文字列を比較するアルゴリズムはシンプルです:
1. 両方の文字列の最初の文字を比較します。
@@ -85,12 +133,51 @@ alert( '01' == 1 ); // true, 文字列 '01' は数値 1 になります
真偽値の場合、`true` は `1` になり、 `false` は `0` になります。:
例:
+=======
+The algorithm to compare two strings is simple:
+
+1. Compare the first character of both strings.
+2. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second. We're done.
+3. Otherwise, if both strings' first characters are the same, compare the second characters the same way.
+4. Repeat until the end of either string.
+5. If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
+
+In the first example above, the comparison `'Z' > 'A'` gets to a result at the first step.
+
+The second comparison `'Glow'` and `'Glee'` needs more steps as strings are compared character-by-character:
+
+1. `G` is the same as `G`.
+2. `l` is the same as `l`.
+3. `o` is greater than `e`. Stop here. The first string is greater.
+
+```smart header="Not a real dictionary, but Unicode order"
+The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it's not exactly the same.
+
+For instance, case matters. A capital letter `"A"` is not equal to the lowercase `"a"`. Which one is greater? The lowercase `"a"`. Why? Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode). We'll get back to specific details and consequences of this in the chapter .
+```
+
+## Comparison of different types
+
+When comparing values of different types, JavaScript converts the values to numbers.
+
+For example:
+
+```js run
+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 example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( true == 1 ); // true
alert( false == 0 ); // true
```
+<<<<<<< HEAD
````smart header="興味深い結果"
次の2つが同時に発生する場合があります:
@@ -98,6 +185,15 @@ alert( false == 0 ); // true
- それらの一方は真偽値の `true` で、もう一方は真偽値の `false`
例:
+=======
+````smart header="A funny consequence"
+It is possible that at the same time:
+
+- Two values are equal.
+- One of them is `true` as a boolean and the other one is `false` as a boolean.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = 0;
@@ -109,23 +205,37 @@ alert( Boolean(b) ); // true
alert(a == b); // true!
```
+<<<<<<< HEAD
JavaScriptの立場からすると、それは普通です。等価チェックは数値変換を使って変換をします(したがって、`"0"` は `0` になります)。一方、 明示的な `Boolean` 変換は別のルールセットを利用します。
````
## 厳密な等価
通常の等価チェック `"=="` は問題を持っています。`0` と `false` を異なるものと判断させることはできません:
+=======
+From JavaScript's standpoint, this result is quite normal. An equality check converts values using the numeric conversion (hence `"0"` becomes `0`), while the explicit `Boolean` conversion uses another set of rules.
+````
+
+## Strict equality
+
+A regular equality check `==` has a problem. It cannot differentiate `0` from `false`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( 0 == false ); // true
```
+<<<<<<< HEAD
空文字列でも同じです:
+=======
+The same thing happens with an empty string:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( '' == false ); // true
```
+<<<<<<< HEAD
これは、異なる型のオペランドは等価演算子 `==` によって数値に変換されるためです。空文字は、ちょうど `false` のように 0 になります。
もしも `0` と `false` を分けたい場合、どうすべきでしょうか?
@@ -150,18 +260,50 @@ alert( 0 === false ); // false, 型が異なるためです
厳密な等価チェック `===` の場合
: それぞれが自身の別々の型に所属しているため、これらの値は異なります。
+=======
+This happens because operands of different types are converted to numbers by the equality operator `==`. An empty string, just like `false`, becomes a zero.
+
+What to do if we'd like to differentiate `0` from `false`?
+
+**A strict equality operator `===` checks the equality without type conversion.**
+
+In other words, if `a` and `b` are of different types, then `a === b` immediately returns `false` without an attempt to convert them.
+
+Let's try it:
+
+```js run
+alert( 0 === false ); // false, because the types are different
+```
+
+There is also a "strict non-equality" operator `!==` analogous to `!=`.
+
+The strict equality operator is a bit longer to write, but makes it obvious what's going on and leaves less room for errors.
+
+## Comparison with null and undefined
+
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( null === undefined ); // false
```
+<<<<<<< HEAD
非厳密なチェック `==` の場合
: 特別なルールがあります。この2つは "スイートカップル" と呼ばれ、(`==` の意味で)等しくなりますが、これら以外の値とは等しいと扱われることはありません。
+=======
+For a non-strict check `==`
+: There's a special rule. These two are a "sweet couple": they equal each other (in the sense of `==`), but not any other value.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( null == undefined ); // true
```
+<<<<<<< HEAD
数学や他の比較 `< > <= >=`
: 値 `null/undefined` は数値に変換されます: `null` は `0` になり、`undefined` は `NaN` (Not a Number)になります。
@@ -170,6 +312,16 @@ alert( 0 === false ); // false, 型が異なるためです
### 奇妙な結果: null vs 0
`null` とゼロを比較してみましょう:
+=======
+For maths and other comparisons `< > <= >=`
+: `null/undefined` are converted to numbers: `null` becomes `0`, while `undefined` becomes `NaN`.
+
+Now let's see some funny things that happen when we apply these rules. And, what's more important, how to not fall into a trap with them.
+
+### Strange result: null vs 0
+
+Let's compare `null` with a zero:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( null > 0 ); // (1) false
@@ -177,6 +329,7 @@ alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) *!*true*/!*
```
+<<<<<<< HEAD
上の3つの例は数学的には奇妙です。最後の結果は "`null` はゼロより大きいまたは等しい" ことを述べています。そうであれば上2つの比較のどちらかは正しくなければいけませんが、両方とも false です。
その理由は等価チェック `==` と比較 `> < >= <=` は異なった処理するためです。比較は `null` を数値に変換します、したがって `0` として扱います。そういう訳で (3) `null >= 0` は true で、 (1) は false になります。
@@ -186,6 +339,17 @@ alert( null >= 0 ); // (3) *!*true*/!*
### 比べるものがない undefined
値 `undefined` は比較に関与しません。:
+=======
+Mathematically, that's strange. The last result states that "`null` is greater than or equal to zero", so in one of the comparisons above it must be `true`, but they are both false.
+
+The reason is that an equality check `==` and comparisons `> < >= <=` work differently. Comparisons convert `null` to a number, treating it as `0`. That's why (3) `null >= 0` is true and (1) `null > 0` is false.
+
+On the other hand, the equality check `==` for `undefined` and `null` is defined such that, without any conversions, they equal each other and don't equal anything else. That's why (2) `null == 0` is false.
+
+### An incomparable undefined
+
+The value `undefined` shouldn't be compared to other values:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( undefined > 0 ); // false (1)
@@ -193,6 +357,7 @@ alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)
```
+<<<<<<< HEAD
なぜそこまでゼロが嫌いなのでしょう?常に false です!
このような結果になった理由は次の通りです:
@@ -214,3 +379,26 @@ alert( undefined == 0 ); // false (3)
- 異なった型の値が比較される場合、それらは数値に変換されます(厳密な等価チェックを除く)
- 値 `null` と `undefined` はそれぞれ等価 `==` であり、それ以外の値とは等価ではありません。
- `>` または `<` のような比較を、`null/undefined` になる可能性のある変数に対して使う場合は注意してください。`null/undefined` を別々にチェックするのが良いアイデアです。
+=======
+Why does it dislike zero so much? Always false!
+
+We get these results because:
+
+- Comparisons `(1)` and `(2)` return `false` because `undefined` gets converted to `NaN` and `NaN` is a special numeric value which returns `false` for all comparisons.
+- The equality check `(3)` returns `false` because `undefined` only equals `null`, `undefined`, and no other value.
+
+### Avoid problems
+
+Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really. Actually, these tricky things will gradually become familiar over time, but there's a solid way to avoid problems with them:
+
+- Treat any comparison with `undefined/null` except the strict equality `===` with exceptional care.
+- Don't use comparisons `>= > < <=` with a variable which may be `null/undefined`, unless you're really sure of what you're doing. If a variable can have these values, check for them separately.
+
+## Summary
+
+- Comparison operators return a boolean value.
+- Strings are compared letter-by-letter in the "dictionary" order.
+- When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).
+- The values `null` and `undefined` equal `==` each other and do not equal any other value.
+- Be careful when using comparisons like `>` or `<` with variables that can occasionally be `null/undefined`. Checking for `null/undefined` separately is a good idea.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 401a857ae5..000af2b6d5 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
@@ -6,7 +6,11 @@ importance: 2
`if..else` 構造を使って、次の内容を尋ねるコードを書いてください: 'JavaScriptの "公式な" 名前は何ですか?'
+<<<<<<< HEAD
もし、訪問者が "ECMAScript" と入力したら、 "Right!" を出力し、それ以外は -- "Didn't know? ECMAScript!" と出力します。
+=======
+If the visitor enters "ECMAScript", then output "Right!", otherwise -- output: "You don't know? ECMAScript!"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b

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 638ce81f13..ff32354fae 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 b13126f949..5ba357a2ed 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,9 +4,15 @@ importance: 5
# 'if' を '?' で書き直しましょう
+<<<<<<< HEAD
三項演算子 `'?'` を使って、この `if` を書き直してください。:
+=======
+Rewrite this `if` using the conditional operator `'?'`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
+let result;
+
if (a + b < 4) {
result = 'Below';
} else {
diff --git a/1-js/02-first-steps/10-ifelse/article.md b/1-js/02-first-steps/10-ifelse/article.md
index b58c8ff7ea..dc7c0438b9 100644
--- a/1-js/02-first-steps/10-ifelse/article.md
+++ b/1-js/02-first-steps/10-ifelse/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 条件分岐: if, '?'
時には、条件に基づき異なるアクションを実行する必要があります。
@@ -5,10 +6,23 @@
そのための `if` 文と、 "疑問符" 演算子とも呼ばれる条件付き演算子(3項演算子) `"?"` があります。
## "if" 文
+=======
+# Conditional branching: if, '?'
+
+Sometimes, we need to perform different actions based on different conditions.
+
+To do that, we can use the `if` statement and the conditional operator `?`, that's also called a "question mark" operator.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
"if" 文は与えられた条件を評価します。結果が `true` であればコードを実行します。
+<<<<<<< HEAD
例:
+=======
+The `if(...)` statement evaluates a condition in parentheses and, if the result is `true`, executes a block of code.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let year = prompt('In which year was ECMAScript-2015 specification published?', '');
@@ -18,9 +32,15 @@ if (year == 2015) alert( 'You are right!' );
*/!*
```
+<<<<<<< HEAD
上の例は、シンプルな等価チェック(`year == 2015`)ですが、より複雑にすることもできます。
実行する文が複数ある場合、コードブロックを波括弧で囲む必要があります。:
+=======
+In the example above, the condition is a simple equality check (`year == 2015`), but it can be much more complex.
+
+If we want to execute more than one statement, we have to wrap our code block inside curly braces:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (year == 2015) {
@@ -29,16 +49,29 @@ if (year == 2015) {
}
```
+<<<<<<< HEAD
たとえ1つの文しかない場合でも `if` を使用するときは波括弧 `{}` でコードブロックを囲むことを推奨します。これは可読性を向上させます。
+=======
+We recommend wrapping your code block with curly braces `{}` every time you use an `if` statement, even if there is only one statement to execute. Doing so improves readability.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## Boolean 変換
+<<<<<<< HEAD
`if (…)` 文は括弧の中の式を評価し、Boolean型に変換します。
+=======
+The `if (…)` statement evaluates the expression in its parentheses and converts the result to a boolean.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
チャプター の変換ルールを思い出してみましょう:
+<<<<<<< HEAD
- 数値 `0`, 空文字 `""`, `null`, `undefined` そして `NaN` は `false` になります。そのため、これらは "偽とみなされる" 値とよばれています。
- 他の値は `true` になるため、"真とみなされる" 値と呼ばれます。
+=======
+- A number `0`, an empty string `""`, `null`, `undefined`, and `NaN` all become `false`. Because of that they are called "falsy" values.
+- Other values become `true`, so they are called "truthy".
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
さて、下のコードですがこの条件は決して実行されません:
@@ -48,7 +81,11 @@ if (0) { // 0 は偽
}
```
+<<<<<<< HEAD
また、この条件は -- 常に処理されます:
+=======
+...and inside this condition -- it always will:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (1) { // 1 は真
@@ -56,7 +93,11 @@ if (1) { // 1 は真
}
```
+<<<<<<< HEAD
次のように事前評価されたBool値を `if` に通すこともできます:
+=======
+We can also pass a pre-evaluated boolean value to `if`, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let cond = (year == 2015); // == は true または false を評価する
@@ -68,11 +109,15 @@ if (cond) {
## "else" 句
+<<<<<<< HEAD
`if` 文は任意の "else" ブロックを持つ場合があり、それは条件が偽の場合に実行されます。
+=======
+The `if` statement may contain an optional `else` block. It executes when the condition is falsy.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
```js run
-let year = prompt('In which year was ECMAScript-2015 specification published?', '');
+let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
if (year == 2015) {
alert( 'You guessed it right!' );
@@ -83,12 +128,16 @@ if (year == 2015) {
## いくつかの条件: "else if"
+<<<<<<< HEAD
いくつかの条件のパターンをテストしたい時があります。そのために `else if` 句があります。
+=======
+Sometimes, we'd like to test several variants of a condition. The `else if` clause lets us do that.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
```js run
-let year = prompt('In which year was ECMAScript-2015 specification published?', '');
+let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
if (year < 2015) {
alert( 'Too early...' );
@@ -99,6 +148,7 @@ if (year < 2015) {
}
```
+<<<<<<< HEAD
上のコードで、JavaScriptは最初に `year < 2015` をチェックします。それが偽の場合、次の条件 `year > 2015` の判定を行います。それもまた偽の場合、最後の `alert` を表示します。
複数の `else if` ブロックを持つことができます。最後の `else` は任意です。
@@ -106,6 +156,15 @@ if (year < 2015) {
## 3項演算子 '?'
条件に依存して変数へ代入を行う必要がある場合があります。
+=======
+In the code above, JavaScript first checks `year < 2015`. If that is falsy, it goes to the next condition `year > 2015`. If that is also falsy, it shows the last `alert`.
+
+There can be more `else if` blocks. The final `else` is optional.
+
+## Conditional operator '?'
+
+Sometimes, we need to assign a variable depending on a condition.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
@@ -124,16 +183,26 @@ if (age > 18) {
alert(accessAllowed);
```
+<<<<<<< HEAD
いわゆる、"条件付き" もしくは "疑問符" 演算子では、より短く簡単に行うことができます。
演算子は疑問符 `"?"` で表されます。演算子が3つのオペランドを持つことから、 "三項演算子" と呼ばれることもあります。これは、JavaScriptの中で3つのオペランドを持つ唯一の演算子です。
+=======
+The so-called "conditional" or "question mark" operator lets us do that in a shorter and simpler way.
+
+The operator is represented by a question mark `?`. Sometimes it's called "ternary", because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
構文は次の通りです:
```js
-let result = condition ? value1 : value2
+let result = condition ? value1 : value2;
```
+<<<<<<< HEAD
`condition` は評価され、もしも真であれば、`value1` が返却され、そうでなければ -- `value2` になります。
+=======
+The `condition` is evaluated: if it's truthy then `value1` is returned, otherwise -- `value2`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
@@ -141,9 +210,15 @@ let result = condition ? value1 : value2
let accessAllowed = (age > 18) ? true : false;
```
+<<<<<<< HEAD
技術的には、`age > 18` の周りの括弧を省くことができます。疑問符演算子は低い優先順位を持っているので、比較 `>` の後に実行されます。
以下の例は上の例と同じように動作します:
+=======
+Technically, we can omit the parentheses around `age > 18`. The question mark operator has a low precedence, so it executes after the comparison `>`.
+
+This example will do the same thing as the previous one:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 比較演算子 "age > 18" が最初に実行されます
@@ -151,10 +226,17 @@ let accessAllowed = (age > 18) ? true : false;
let accessAllowed = age > 18 ? true : false;
```
+<<<<<<< HEAD
しかし、括弧はコードの可読性をより良くします。そのため、括弧を使うことが推奨されます。
````smart
上の例では、比較自体が `true/false` を返すため、疑問符演算子を回避することが可能です。
+=======
+But parentheses make the code more readable, so we recommend using them.
+
+````smart
+In the example above, you can avoid using the question mark operator because the comparison itself returns `true/false`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// the same
@@ -164,7 +246,11 @@ let accessAllowed = age > 18;
## 複数の '?'
+<<<<<<< HEAD
連続する疑問符 `"?"` 演算子は1つ以上の条件に依存した値を返すことができます。
+=======
+A sequence of question mark operators `?` can return a value that depends on more than one condition.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
```js run
@@ -178,6 +264,7 @@ let message = (age < 3) ? 'Hi, baby!' :
alert( message );
```
+<<<<<<< HEAD
最初、それが何をしているのか掴むのが難しいかもしれません。しかしよく見るとそれがただの通常の一連のテストであることがわかります。
1. 最初の疑問符は `age < 3` かどうかチェックします。
@@ -186,11 +273,21 @@ alert( message );
4. それが真であれば -- `'Greetings!'` を返します。そうでなければ -- コロン `":"` の後に行き、`What an unusual age` を返します。
`if..else` を使った同じロジックです:
+=======
+It may be difficult at first to grasp what's going on. But after a closer look, we can see that it's just an ordinary sequence of tests:
+
+1. The first question mark checks whether `age < 3`.
+2. If true -- it returns `'Hi, baby!'`. Otherwise, it continues to the expression after the colon ":", checking `age < 18`.
+3. If that's true -- it returns `'Hello!'`. Otherwise, it continues to the expression after the next colon ":", checking `age < 100`.
+4. If that's true -- it returns `'Greetings!'`. Otherwise, it continues to the expression after the last colon ":", returning `'What an unusual age!'`.
+
+Here's how this looks using `if..else`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (age < 3) {
message = 'Hi, baby!';
-} else if (a < 18) {
+} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
@@ -201,7 +298,11 @@ if (age < 3) {
## 非伝統的な '?' の使用
+<<<<<<< HEAD
時々、疑問符 `'?'` は `if` の置換として使われます:
+=======
+Sometimes the question mark `?` is used as a replacement for `if`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
let company = prompt('Which company created JavaScript?', '');
@@ -212,6 +313,7 @@ let company = prompt('Which company created JavaScript?', '');
*/!*
```
+<<<<<<< HEAD
条件 `company == 'Netscape'` に応じて、`"?"` の後の1つ目もしくは2つ目の部分が実行されアラートが表示されます。
ここでは変数に結果を代入していません。このアイデアは条件に応じて異なるコードを実行させるものです。
@@ -221,6 +323,17 @@ let company = prompt('Which company created JavaScript?', '');
表記は `if` よりも短いように見え、一部のプログラマには魅力的です。しかしそれは読みにくいです。
比較として `if` を使った同じコードです:
+=======
+Depending on the condition `company == 'Netscape'`, either the first or the second expression after the `?` gets executed and shows an alert.
+
+We don't assign a result to a variable here. Instead, we execute different code depending on the condition.
+
+**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.
+
+Here is the same code using `if` for comparison:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
let company = prompt('Which company created JavaScript?', '');
@@ -234,6 +347,12 @@ if (company == 'Netscape') {
*/!*
```
+<<<<<<< HEAD
私たちの目はコードを縦に見ていきます。複数行にまたがる構造は、長い水平な命令セットよりも理解しやすいです。
疑問符 `'?'` の目的は、条件によって別の値を返すことです。まさにそのために使ってください。異なるコードの枝葉を実行するために `if` があります。
+=======
+Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.
+
+The purpose of the question mark operator `?` is to return one value or another depending on its condition. Please use it for exactly that. Use `if` when you need to execute different branches of code.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md
index fdba6dbd82..b3315e1a1f 100644
--- a/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md
+++ b/1-js/02-first-steps/11-logical-operators/1-alert-null-2-undefined/task.md
@@ -4,7 +4,11 @@ importance: 5
# OR の結果はなんでしょう?
+<<<<<<< HEAD
下のコードは何を出力するでしょう?
+=======
+What is the code below going to output?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( null || 2 || undefined );
diff --git a/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md b/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md
index 9f45e4b68d..a7ff585bfc 100644
--- a/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md
+++ b/1-js/02-first-steps/11-logical-operators/2-alert-or/solution.md
@@ -6,8 +6,14 @@ alert( alert(1) || 2 || alert(3) );
`alert` の呼び出しは値を返しません。また、言い換えると、 `undefined` を返します。
+<<<<<<< HEAD
1. 最初の OR `||` はその左のオペランド `alert(1)` を検査します。それは `1` の最初のメッセージを表示します。
2. `alert` は `undefined` を返すので、OR は真値を探すのに2つ目のオペランドに行きます。
3. 2つ目のペランド `2` は真値なので、実行が中止され `2` が返却されます。次に外部の alert でそれが表示されます。
+=======
+1. The first OR `||` evaluates its left operand `alert(1)`. That shows the first message with `1`.
+2. The `alert` returns `undefined`, so OR goes on to the second operand searching for a truthy value.
+3. The second operand `2` is truthy, so the execution is halted, `2` is returned and then shown by the outer alert.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
検査は `alert(3)` に到達しないので、 `3` は現れません。
diff --git a/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md b/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md
index d47e8079b1..8ea50fbf7e 100644
--- a/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md
+++ b/1-js/02-first-steps/11-logical-operators/2-alert-or/task.md
@@ -4,7 +4,11 @@ importance: 3
# OR されたアラートの結果は何ですか?
+<<<<<<< HEAD
下のコードは何を出力するでしょう?
+=======
+What will the code below output?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( alert(1) || 2 || alert(3) );
diff --git a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md
index f727d5f9b2..8e620271e9 100644
--- a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md
+++ b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/solution.md
@@ -1,5 +1,5 @@
答え: `null` です。なぜなら、それがリストの中の最初の偽値だからです。
```js run
-alert( 1 && null && 2 );
+alert(1 && null && 2);
```
diff --git a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md
index 94b47c7b0a..0392329063 100644
--- a/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md
+++ b/1-js/02-first-steps/11-logical-operators/3-alert-1-null-2/task.md
@@ -4,7 +4,11 @@ importance: 5
# AND の結果は何?
+<<<<<<< HEAD
このコードは何を表示するでしょう?
+=======
+What is this code going to show?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( 1 && null && 2 );
diff --git a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md
index 8261b19498..7e4af734f5 100644
--- a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md
+++ b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/solution.md
@@ -12,4 +12,9 @@ AND `&&` の優先順位は `||` よりも高いので、最初に実行され
null || 3 || 4
```
+<<<<<<< HEAD
これの最初の真値の結果なので、`3` です。
+=======
+Now the result is the first truthy value: `3`.
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md
index 0193df66a8..122be2a581 100644
--- a/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md
+++ b/1-js/02-first-steps/11-logical-operators/5-alert-and-or/task.md
@@ -4,7 +4,11 @@ importance: 5
# OR AND OR の結果
+<<<<<<< HEAD
結果はどうなるでしょう?
+=======
+What will the result be?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( null || 2 && 3 || 4 );
diff --git a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md
index a9f245041f..17bbcbcb5e 100644
--- a/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md
+++ b/1-js/02-first-steps/11-logical-operators/6-check-if-in-range/task.md
@@ -4,6 +4,10 @@ importance: 3
# 範囲内のチェック
+<<<<<<< HEAD
包括的に `age` が `14` と `90` の間かをチェックする `if` 条件を書きなさい。
+=======
+Write an `if` condition to check that `age` is between `14` and `90` inclusively.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
"包括的に" は `age` が `14` または `90` の端に到達できることを意味します。
diff --git a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md
index 60000109d6..6b511ffd7e 100644
--- a/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md
+++ b/1-js/02-first-steps/11-logical-operators/7-check-if-out-range/task.md
@@ -4,6 +4,10 @@ importance: 3
# 範囲外のチェック
+<<<<<<< HEAD
包括的に `age` が 14 と 90 間ではないことをチェックするための `if` 条件を書きなさい。
+=======
+Write an `if` condition to check that `age` is NOT between `14` and `90` inclusively.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
2つのバリアントを作ってください: 最初は NOT `!` を使い、2つ目は -- それなしです。
diff --git a/1-js/02-first-steps/11-logical-operators/8-if-question/task.md b/1-js/02-first-steps/11-logical-operators/8-if-question/task.md
index d92b499b0e..5e1b012583 100644
--- a/1-js/02-first-steps/11-logical-operators/8-if-question/task.md
+++ b/1-js/02-first-steps/11-logical-operators/8-if-question/task.md
@@ -6,7 +6,11 @@ importance: 5
これらの `alert` で実行されるのはどれでしょう?
+<<<<<<< HEAD
`if(...)` の内側の式の結果はどうなるでしょう?
+=======
+What will the results of the expressions be inside `if(...)`?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (-1 || 0) alert( 'first' );
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 b46558f985..6dcaef0cb3 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
@@ -22,4 +22,8 @@ if (userName === 'Admin') {
}
```
+<<<<<<< HEAD
`if` ブロック内の縦のインデントに注意してください。技術的には必須ではありませんが、コードの可読性をより良くします。
+=======
+Note the vertical indents inside the `if` blocks. They are technically not required, but make the code more readable.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 bcedacb062..54a420b6fb 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
@@ -2,6 +2,7 @@ importance: 3
---
+<<<<<<< HEAD
# ログインのチェック
`prompt` でログインを要求するコードを書いてください。
@@ -20,5 +21,26 @@ importance: 3

入れ子の `if` ブロックを使ってください。コードの全体的な読みやすさに気をつけてください。
+=======
+# Check the login
+
+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".
+
+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"
+
+The schema:
+
+
+
+Please use nested `if` blocks. Mind the overall readability of the code.
+
+Hint: passing an empty input to a prompt returns an empty string `''`. Pressing `key:ESC` during a prompt returns `null`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
[demo]
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 e4841fd332..2e8ad8ceb5 100644
--- a/1-js/02-first-steps/11-logical-operators/article.md
+++ b/1-js/02-first-steps/11-logical-operators/article.md
@@ -1,22 +1,40 @@
# 論理演算子
+<<<<<<< HEAD
JavaScriptには4つの論理演算子があります: `||` (OR:論理和), `&&` (AND:論理積), `!` (NOT:否定), `??` (Null合体)。ここでは最初の3つを説明し、`??` 演算子は次の記事で説明します。
これらは "論理" と呼ばれますが、Boolean 型だけでなく、どの型の値にも適用することができます。結果もまた任意の型になります。
+=======
+There are four logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT), `??` (Nullish Coalescing). Here we cover the first three, the `??` operator is in the next article.
+
+Although they are called "logical", they can be applied to values of any type, not only boolean. Their result can also be of any type.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
では、詳細を見ていきましょう。
+<<<<<<< HEAD
## || (OR)
"OR" 演算子は2つの縦の記号で表現されます:
+=======
+## || (OR)
+
+The "OR" operator is represented with two vertical line symbols:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
result = a || b;
```
+<<<<<<< HEAD
古典的なプログラミングでは、論理和は真偽値のみを操作することを意味していました。もしもその引数のいずれかが `true` の場合、それは `true` を返します。そうでなければ `false` を返します。
JavaScriptでは、演算子は少し難解ですが強力です。最初に真偽値で起こることを見てみましょう。
+=======
+In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are `true`, it returns `true`, otherwise it returns `false`.
+
+In JavaScript, the operator is a little bit trickier and more powerful. But first, let's see what happens with boolean values.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
4つの取りうる論理的な組み合わせがあります:
@@ -29,9 +47,15 @@ alert( false || false ); // false
ご覧の通り、両方のオペランドが `false` の場合を除き、結果は常に `true` です。
+<<<<<<< HEAD
もしもオペランドが Boolean でない場合、評価のために Boolean に変換されます。
例えば、数値 `1` は `true` として扱われ、数値 `0` は `false` となります:
+=======
+If an operand is not a boolean, it's converted to a boolean for the evaluation.
+
+For instance, the number `1` is treated as `true`, the number `0` as `false`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
if (1 || 0) { // if( true || false ) のように動作します
@@ -39,7 +63,11 @@ if (1 || 0) { // if( true || false ) のように動作します
}
```
+<<<<<<< HEAD
ほとんどの場合、OR `||` は `if` 文の中で、与えられた条件のいずれかが正しいかを確認するのに使われます。
+=======
+Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is `true`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
@@ -64,9 +92,15 @@ if (hour < 10 || hour > 18 || isWeekend) {
}
```
+<<<<<<< HEAD
## OR は最初の真値を探します
上で描かれたロジックはいくらか古典的です。ここで JavaScriptの特別な機能を持ってきましょう。
+=======
+## 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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
拡張されたアルゴリズムは次の通りに動作します。
@@ -76,19 +110,32 @@ if (hour < 10 || hour > 18 || isWeekend) {
result = value1 || value2 || value3;
```
+<<<<<<< HEAD
OR `"||"` 演算子は次のように動きます:
- 左から右にオペランドを評価します。
- それぞれのオペランドで、それを Boolean に変換します。もしも結果が `true` であれば、停止しオペランドの本来の値を返します。
- もしもすべての他のオペランドが評価された場合(i.e. すべて `偽` のとき), 最後のオペランドを返します。
+=======
+The OR `||` operator does the following:
+
+- Evaluates operands from left to right.
+- For each operand, converts it to boolean. If the result is `true`, stops and returns the original value of that operand.
+- If all operands have been evaluated (i.e. all were `false`), returns the last operand.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
値は変換されていない元の形式で返却されます。
+<<<<<<< HEAD
つまり、OR `"||"` のチェーンは最初に真となる値を返し、そのような値がない場合には最後のオペランドが返却されます。
+=======
+In other words, a chain of OR `||` returns the first truthy value or the last one if no truthy value is found.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
```js run
+<<<<<<< HEAD
alert( 1 || 0 ); // 1 (1 は真)
alert( null || 1 ); // 1 (1 は最初の真値)
@@ -104,6 +151,23 @@ alert( undefined || null || 0 ); // 0 (すべて偽、なので最後の値が
例えば、`firstName`, `lastName` と `nickName` 変数があり、すべて任意( undefined あるいは偽となる値になりうる)とします。
データを持っているものを選び、表示する(あるいは何も設定されていな場合は `"Anonymous"`)のに、OR `||` が利用できます:
+=======
+alert( 1 || 0 ); // 1 (1 is truthy)
+
+alert( null || 1 ); // 1 (1 is the first truthy value)
+alert( null || 0 || 1 ); // 1 (the first truthy value)
+
+alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
+```
+
+This leads to some interesting usage compared to a "pure, classical, boolean-only OR".
+
+1. **Getting the first truthy value from a list of variables or expressions.**
+
+ For instance, we have `firstName`, `lastName` and `nickName` variables, all optional (i.e. can be undefined or have falsy values).
+
+ Let's use OR `||` to choose the one that has the data and show it (or `"Anonymous"` if nothing set):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let firstName = "";
@@ -115,6 +179,7 @@ alert( undefined || null || 0 ); // 0 (すべて偽、なので最後の値が
*/!*
```
+<<<<<<< HEAD
すべての変数が偽であれば、`"Anonymous"` が表示されます。
2. **短絡評価(最小評価)**
@@ -126,12 +191,26 @@ alert( undefined || null || 0 ); // 0 (すべて偽、なので最後の値が
この機能の重要性は、オペランドが単なる値ではなく、変数の割当や関数呼び出しなどの副作用のある式である場合に明らかになります。
以下の例を実行した場合、2つ目のメッセージだけが表示されます:
+=======
+ If all variables were falsy, `"Anonymous"` would show up.
+
+2. **Short-circuit evaluation.**
+
+ Another feature of OR `||` operator is the so-called "short-circuit" evaluation.
+
+ It means that `||` processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.
+
+ The importance of this feature becomes obvious if an operand isn't just a value, but an expression with a side effect, such as a variable assignment or a function call.
+
+ In the example below, only the second message is printed:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
*!*true*/!* || alert("not printed");
*!*false*/!* || alert("printed");
```
+<<<<<<< HEAD
1行目では、OR `||` 演算子が `true` を見るとすぐに評価を停止するため、`alert` は実行されません。
条件の左側が false のときにだけコマンドを実行するためにこの特徴を利用する人もいます。
@@ -139,12 +218,25 @@ alert( undefined || null || 0 ); // 0 (すべて偽、なので最後の値が
## && (AND)
AND 演算子は2つのアンパサンド `&&` で表されます:
+=======
+ In the first line, the OR `||` operator stops the evaluation immediately upon seeing `true`, so the `alert` isn't run.
+
+ Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.
+
+## && (AND)
+
+The AND operator is represented with two ampersands `&&`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
result = a && b;
```
+<<<<<<< HEAD
古典的なプログラミングでは、AND は両方のオペランドが真のときに `true` を返します。それ以外の場合は `false` です:
+=======
+In classical programming, AND returns `true` if both operands are truthy and `false` otherwise:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( true && true ); // true
@@ -160,11 +252,15 @@ let hour = 12;
let minute = 30;
if (hour == 12 && minute == 30) {
- alert( 'Time is 12:30' );
+ alert( 'The time is 12:30' );
}
```
+<<<<<<< HEAD
OR のように、AND のオペランドとして任意の値が許可されています:
+=======
+Just as with OR, any value is allowed as an operand of AND:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
if (1 && 0) { // true && false として評価される
@@ -173,7 +269,11 @@ if (1 && 0) { // true && false として評価される
```
+<<<<<<< HEAD
## AND は最初の偽値を探します
+=======
+## AND "&&" finds the first falsy value
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
複数のANDされた値が与えられました:
@@ -181,11 +281,19 @@ if (1 && 0) { // true && false として評価される
result = value1 && value2 && value3;
```
+<<<<<<< HEAD
AND `"&&"` 演算子は次のように動きます:
- 左から右にオペランドを評価します。
- それぞれのオペランドで、それを Boolean に変換します。もしも結果が `false` の場合、ストップしそのオペランドの本来の値を返します。
- もしもすべての他のオペランドが評価された場合(i.e. すべて `真` のとき), 最後のオペランドを返します。
+=======
+The AND `&&` operator does the following:
+
+- Evaluates operands from left to right.
+- For each operand, converts it to a boolean. If the result is `false`, stops and returns the original value of that operand.
+- If all operands have been evaluated (i.e. all were truthy), returns the last operand.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
つまり、ANDは最初の偽値、またはない場合には最後の値を返します。
@@ -217,6 +325,7 @@ alert( 1 && 2 && null && 3 ); // null
alert( 1 && 2 && 3 ); // 3, 最後のオペランド
```
+<<<<<<< HEAD
````smart header="AND `&&` は OR `||` の前に実行します"
AND `&&` 演算子の優先順位は OR `||` よりも高いです。
@@ -225,6 +334,16 @@ AND `&&` 演算子の優先順位は OR `||` よりも高いです。
````warn header="`if` を `||` や `&&` に置き換えないでください"
時々、AND `&&` 演算子を "`if`を短く書く方法" として利用する人がいます。
+=======
+````smart header="Precedence of AND `&&` is higher than OR `||`"
+The precedence of AND `&&` operator is higher than OR `||`.
+
+So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`.
+````
+
+````warn header="Don't replace `if` with `||` or `&&`"
+Sometimes, people use the AND `&&` operator as a "shorter way to write `if`".
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
@@ -234,7 +353,11 @@ let x = 1;
(x > 0) && alert( 'Greater than zero!' );
```
+<<<<<<< HEAD
`&&` の右側のアクションは、その評価に到達した場合にのみ実行されます。つまり: `(x > 0)` が true の場合のみです。
+=======
+The action in the right part of `&&` would execute only if the evaluation reaches it. That is, only if `(x > 0)` is true.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
なので、基本的に同じことをする別の方法があります:
@@ -244,13 +367,21 @@ let x = 1;
if (x > 0) alert( 'Greater than zero!' );
```
+<<<<<<< HEAD
`&&` を含むやり方は、より短いように見えますが、`if` はより明白で、読みやすい傾向にあります。そのため、すべての構文をその目的に合わせて使うことを推奨します。条件判定が必要なら `if` を、論理積が必要なら `&&` を使います。
+=======
+Although, the variant with `&&` appears shorter, `if` is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use `if` if we want `if` and use `&&` if we want AND.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
````
## ! (NOT)
+<<<<<<< HEAD
真偽値否定演算子は感嘆符 `"!"` で表現されます。
+=======
+The boolean NOT operator is represented with an exclamation sign `!`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
構文はとてもシンプルです:
@@ -260,8 +391,13 @@ result = !value;
演算子は1つの引数を取り、次のようにします:
+<<<<<<< HEAD
1. オペランドを真偽値型に変換します: `true/false`。
2. 逆の値を返します。
+=======
+1. Converts the operand to boolean type: `true/false`.
+2. Returns the inverse value.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例:
@@ -277,7 +413,11 @@ alert( !!"non-empty string" ); // true
alert( !!null ); // false
```
+<<<<<<< HEAD
つまり、最初の NOT は値を真偽値に変換しその逆を返します。そして、2つ目の NOT は再びその逆をします。最終的に、明示的な値からブール値への変換を行います。
+=======
+That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
少し冗長ですが同じことをする方法があります -- 組み込みの `Boolean` 関数です。:
@@ -286,4 +426,8 @@ alert( Boolean("non-empty string") ); // true
alert( Boolean(null) ); // false
```
+<<<<<<< HEAD
NOT `!` の優先順はすべての論理演算子でもっとも高いので、`&&` や `||` よりも常に最初に実行されます。
+=======
+The precedence of NOT `!` is the highest of all logical operators, so it always executes first, before `&&` or `||`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/12-nullish-coalescing-operator/article.md b/1-js/02-first-steps/12-nullish-coalescing-operator/article.md
index fe1db3bfc9..2fb7409219 100644
--- a/1-js/02-first-steps/12-nullish-coalescing-operator/article.md
+++ b/1-js/02-first-steps/12-nullish-coalescing-operator/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# NULL合体演算子(Nullish coalescing operator) '??'
[recent browser="new"]
@@ -15,28 +16,63 @@ NULL合体演算子は2つの疑問符 `??` で記述されます。
NULL合体演算子はまったく新しいものではありません。2つのうちから、最初の "定義済み" の値を取得するには良い構文です。
既に知っている演算子を使用して `result = a ?? b` を書き直すことができます:
+=======
+# Nullish coalescing operator '??'
+
+[recent browser="new"]
+
+The nullish coalescing operator is written as two question marks `??`.
+
+As it treats `null` and `undefined` similarly, we'll use a special term here, in this article. For brevity, we'll say that a value is "defined" when it's neither `null` nor `undefined`.
+
+The result of `a ?? b` is:
+- if `a` is defined, then `a`,
+- if `a` isn't defined, then `b`.
+
+In other words, `??` returns the first argument if it's not `null/undefined`. Otherwise, the second one.
+
+The nullish coalescing operator isn't anything completely new. It's just a nice syntax to get the first "defined" value of the two.
+
+We can rewrite `result = a ?? b` using the operators that we already know, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
result = (a !== null && a !== undefined) ? a : b;
```
+<<<<<<< HEAD
これで、`??` がすることがなにか明確ですね。これがどこで役立つが見ていきましょう。
`??` の一般的なユースケースは、潜在的に未定義の変数のデフォルト値を提供することです。
例えば、ここでは定義済みであれば `user` を、そうでなければ `Anonymous` を表示します:
+=======
+Now it should be absolutely clear what `??` does. Let's see where it helps.
+
+The common use case for `??` is to provide a default value.
+
+For example, here we show `user` if its value isn't `null/undefined`, otherwise `Anonymous`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let user;
+<<<<<<< HEAD
alert(user ?? "Anonymous"); // Anonymous (user は未定義)
```
こちらは名前が割り当てられた `user` の例です:
+=======
+alert(user ?? "Anonymous"); // Anonymous (user is undefined)
+```
+
+Here's the example with `user` assigned to a name:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let user = "John";
+<<<<<<< HEAD
alert(user ?? "Anonymous"); // John (user は定義済み)
```
@@ -47,35 +83,64 @@ alert(user ?? "Anonymous"); // John (user は定義済み)
これらの変数の1つを使用してユーザ名を表示、あるいはすべて未定義の場合には "Anonymous" と表示したいです。
そのために `??` 演算子を使用しましょう:
+=======
+alert(user ?? "Anonymous"); // John (user is not null/undefined)
+```
+
+We can also use a sequence of `??` to select the first value from a list that isn't `null/undefined`.
+
+Let's say we have a user's data in variables `firstName`, `lastName` or `nickName`. All of them may be not defined, if the user decided not to fill in the corresponding values.
+
+We'd like to display the user name using one of these variables, or show "Anonymous" if all of them are `null/undefined`.
+
+Let's use the `??` operator for that:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let firstName = null;
let lastName = null;
let nickName = "Supercoder";
+<<<<<<< HEAD
// 最初の null/undefined でない値を表示します
+=======
+// shows the first defined value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
*/!*
```
+<<<<<<< HEAD
## || との比較
[前のチャプター](info:logical-operators#or-finds-the-first-truthy-value) で説明したように、OR `||` 演算子は `??` と同じ方法で利用することができます。
例えば、上のコードで `??` を `||` に置き換えることができ、同じ結果を得ることができます:
+=======
+## Comparison with ||
+
+The OR `||` operator can be used in the same way as `??`, as it was described in the [previous chapter](info:logical-operators#or-finds-the-first-truthy-value).
+
+For example, in the code above we could replace `??` with `||` and still get the same result:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let firstName = null;
let lastName = null;
let nickName = "Supercoder";
+<<<<<<< HEAD
// 最初の真値を表示
+=======
+// shows the first truthy value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
alert(firstName || lastName || nickName || "Anonymous"); // Supercoder
*/!*
```
+<<<<<<< HEAD
歴史的には、OR `||` 演算子が最初にありました。JavaScript の登場以来存在しているため、開発者は長い間そのような目的で使用していました。
一方、NULL合体演算子 `??` が JavaScript に追加されたのは最近のことで、その理由は人々が `||` にあまり満足していなかったためです。
@@ -89,6 +154,21 @@ alert(firstName || lastName || nickName || "Anonymous"); // Supercoder
ただし、実際には、変数が `null/undefined` の場合にのみデフォルト値を使用したい場合があります。つまり、値が本当に未知/設定されていない場合です。
例として次を考えましょう:
+=======
+Historically, the OR `||` operator was there first. It's been there since the beginning of JavaScript, so developers were using it for such purposes for a long time.
+
+On the other hand, the nullish coalescing operator `??` was added to JavaScript only recently, and the reason for that was that people weren't quite happy with `||`.
+
+The important difference between them is that:
+- `||` returns the first *truthy* value.
+- `??` returns the first *defined* value.
+
+In other words, `||` doesn't distinguish between `false`, `0`, an empty string `""` and `null/undefined`. They are all the same -- falsy values. If any of these is the first argument of `||`, then we'll get the second argument as the result.
+
+In practice though, we may want to use default value only when the variable is `null/undefined`. That is, when the value is really unknown/not set.
+
+For example, consider this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let height = 0;
@@ -97,6 +177,7 @@ alert(height || 100); // 100
alert(height ?? 100); // 0
```
+<<<<<<< HEAD
- `height || 100` は `height` が偽値になるかをチェックし、それは `0` であり偽です。
- なので、`||` の結果は2つ目の引数である `100` です。
- `height ?? 100` は `height` が `null/undefined` かをチェックしますが、そうではありません。
@@ -111,17 +192,38 @@ alert(height ?? 100); // 0
つまり、`||` と同様に NULL合体演算子 `??` は `=` と `?` の前に評価されますが、`+` や `*` などの他のほとんどの演算子の後に評価されます。
したがって、他の演算子を含む式で `??` で値を選択したい場合は、括弧を追加することを検討してください:
+=======
+- The `height || 100` checks `height` for being a falsy value, and it's `0`, falsy indeed.
+ - so the result of `||` is the second argument, `100`.
+- The `height ?? 100` checks `height` for being `null/undefined`, and it's not,
+ - so the result is `height` "as is", that is `0`.
+
+In practice, the zero height is often a valid value, that shouldn't be replaced with the default. So `??` does just the right thing.
+
+## Precedence
+
+The precedence of the `??` operator is the same as `||`. They both equal `3` in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table).
+
+That means that, just like `||`, the nullish coalescing operator `??` is evaluated before `=` and `?`, but after most other operations, such as `+`, `*`.
+
+So we may need to add parentheses in expressions like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let height = null;
let width = null;
+<<<<<<< HEAD
// 重要: 括弧を使用します
+=======
+// important: use parentheses
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let area = (height ?? 100) * (width ?? 50);
alert(area); // 5000
```
+<<<<<<< HEAD
そうでない場合、括弧を省略すると `*` は `??` よりも優先度が高いため、最初に実行され、正しくない結果になるでしょう。
```js
@@ -137,11 +239,29 @@ let area = height ?? (100 * width) ?? 50;
安全上の理由により、JavaScript は優先順位が括弧で明示的に指定されていない限り、`&&` や `||` 演算子と一緒に `??` を用いることを禁止しています。
次のコードは構文エラーになります:
+=======
+Otherwise, if we omit parentheses, then as `*` has the higher precedence than `??`, it would execute first, leading to incorrect results.
+
+```js
+// without parentheses
+let area = height ?? 100 * width ?? 50;
+
+// ...works this way (not what we want):
+let area = height ?? (100 * width) ?? 50;
+```
+
+### Using ?? with && or ||
+
+Due to safety reasons, JavaScript forbids using `??` together with `&&` and `||` operators, unless the precedence is explicitly specified with parentheses.
+
+The code below triggers a syntax error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let x = 1 && 2 ?? 3; // Syntax error
```
+<<<<<<< HEAD
この制限には当然議論の余地がありますが、人々が `||` から `??` に切り替え始めるときに、プログラミングのミスを避ける目的で言語仕様に追加されました。
回避するには明示的に括弧を使用します:
@@ -149,11 +269,21 @@ let x = 1 && 2 ?? 3; // Syntax error
```js run
*!*
let x = (1 && 2) ?? 3; // 動作します
+=======
+The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from `||` to `??`.
+
+Use explicit parentheses to work around it:
+
+```js run
+*!*
+let x = (1 && 2) ?? 3; // Works
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(x); // 2
```
+<<<<<<< HEAD
## サマリ
- Null合体演算子 `??` は一覧から "定義済み" の値を選択するための簡単な方法を提供します。
@@ -167,3 +297,18 @@ alert(x); // 2
- 演算子 `??` は優先度が低く、`?` や `=` よりも少し高い程度です。そのため、式の中で使用する際には括弧を追加することを検討してください。
- 明示的な括弧なしに `||` や `&&` と一緒に利用することは禁止されています。
+=======
+## Summary
+
+- The nullish coalescing operator `??` provides a short way to choose the first "defined" value from a list.
+
+ It's used to assign default values to variables:
+
+ ```js
+ // set height=100, if height is null or undefined
+ height = height ?? 100;
+ ```
+
+- The operator `??` has a very low precedence, only a bit higher than `?` and `=`, so consider adding parentheses when using it in an expression.
+- It's forbidden to use it with `||` or `&&` without explicit parentheses.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md b/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md
index c6bda96ffd..9078953aeb 100644
--- a/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md
+++ b/1-js/02-first-steps/13-while-for/1-loop-last-value/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
答え: `1`.
+=======
+The answer: `1`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 3;
@@ -8,13 +12,20 @@ while (i) {
}
```
+<<<<<<< HEAD
各ループイテレーションは `i` を `1` 減らします。チェック `while(i)` は `i = 0` のときにループを停止します。
従って、ループのステップは次のシーケンスを形成します。:
+=======
+Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`.
+
+Hence, the steps of the loop form the following sequence ("loop unrolled"):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let i = 3;
+<<<<<<< HEAD
alert(i--); // 3 を表示, i を 2 に減らす
alert(i--) // 2 を表示, i を 1 に減らす
@@ -22,4 +33,13 @@ alert(i--) // 2 を表示, i を 1 に減らす
alert(i--) // 1 を表示, i を 0 に減らす
// 完了。while(i)チェックでループが停止します。
+=======
+alert(i--); // shows 3, decreases i to 2
+
+alert(i--) // shows 2, decreases i to 1
+
+alert(i--) // shows 1, decreases i to 0
+
+// done, while(i) check stops the loop
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
diff --git a/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md b/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md
index 4792b925bb..62ee896016 100644
--- a/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md
+++ b/1-js/02-first-steps/13-while-for/1-loop-last-value/task.md
@@ -2,9 +2,15 @@ importance: 3
---
+<<<<<<< HEAD
# 最後のループ値
このコードで最後にアラートされる値は何でしょう?それはなぜでしょう?
+=======
+# Last loop value
+
+What is the last value alerted by this code? Why?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let i = 3;
diff --git a/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md b/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md
index a1f3a01dcc..3c00bfb881 100644
--- a/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md
+++ b/1-js/02-first-steps/13-while-for/2-which-value-while/solution.md
@@ -1,24 +1,40 @@
+<<<<<<< HEAD
このタスクは、ポストフィックス/サフィックス形式を比較で使ったときに、どのように異なる結果に繋がるかを示します。
1. **1 から 4**
+=======
+The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons.
+
+1. **From 1 to 4**
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 0;
while (++i < 5) alert( i );
```
+<<<<<<< HEAD
最初の値は `i=1` です。なぜなら、`i++` は最初に `i` をインクリメントし、新しい値を返します。なので、最初の比較は `1 < 5` で、`alert` は `1` を表示します。
次に、`2,3,4…` に続きます -- 値は次々に表示されます。比較は常にインクリメントされた値を使います。なぜなら `++` は変数の前にあるからです。
最終的に、`i=4` では `5` にインクリメントされ、比較 `while(5 < 5)` が偽になりループが停止します。なので、`5` は表示されません。
2. **1 から 5**
+=======
+ The first value is `i = 1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`.
+
+ Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable.
+
+ Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown.
+2. **From 1 to 5**
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 0;
while (i++ < 5) alert( i );
```
+<<<<<<< HEAD
最初の値は再び `i=1` です。`i++` のポストフィックス形式は `i` をインクリメントし、*古い* 値を返します。なので、比較 `i++ < 5` は `i=0` を使います (`++i < 5` とは逆です)。
しかし、`alert` 呼び出しは別です。インクリメントと比較の後に実行される別の文なので、現在の `i=1` を使います。
@@ -29,3 +45,14 @@
値 `i=5` は最後です。なぜなら次のステップ `while(5 < 5)` は偽になるからです。
+=======
+ The first value is again `i = 1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i = 0` (contrary to `++i < 5`).
+
+ But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i = 1`.
+
+ Then follow `2, 3, 4…`
+
+ Let's stop on `i = 4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`.
+
+ The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/2-which-value-while/task.md b/1-js/02-first-steps/13-while-for/2-which-value-while/task.md
index 4acb7805c4..0eac594299 100644
--- a/1-js/02-first-steps/13-while-for/2-which-value-while/task.md
+++ b/1-js/02-first-steps/13-while-for/2-which-value-while/task.md
@@ -2,6 +2,7 @@ importance: 4
---
+<<<<<<< HEAD
# while でどの値が表示される?
各ループで、どの値が表示されるか、あなたの意見を書きなさい。また、それと答えを見比べてみてください。
@@ -9,12 +10,25 @@ importance: 4
両方のループは同じ数だけ `alert` されますか?それとも違いますか?
1. プレフィックス形式 `++i`:
+=======
+# Which values does the while loop show?
+
+For every loop iteration, write down which value it outputs and then compare it with the solution.
+
+Both loops `alert` the same values, or not?
+
+1. The prefix form `++i`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let i = 0;
while (++i < 5) alert( i );
```
+<<<<<<< HEAD
2. ポストフィックス形式 `i++`
+=======
+2. The postfix form `i++`
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let i = 0;
diff --git a/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md b/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md
index 90ef539d2f..cbf132847f 100644
--- a/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md
+++ b/1-js/02-first-steps/13-while-for/3-which-value-for/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
**答え: どちらも場合も `0` から `4` です**
+=======
+**The answer: from `0` to `4` in both cases.**
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
for (let i = 0; i < 5; ++i) alert( i );
@@ -6,6 +10,7 @@ for (let i = 0; i < 5; ++i) alert( i );
for (let i = 0; i < 5; i++) alert( i );
```
+<<<<<<< HEAD
これは `for` のアルゴリズムから簡単に差し引くことができます:
1. すべての前(最初)に `i = 0` を一度実行します。
@@ -15,3 +20,14 @@ for (let i = 0; i < 5; i++) alert( i );
インクリメント `i++` は条件チェック (2) とは分離されています。それは単に別の文です。
インクリメントによって返された値はここでは使われていません。なので、 `i++` と `++i` の間に違いはありません。
+=======
+That can be easily deducted from the algorithm of `for`:
+
+1. Execute once `i = 0` before everything (begin).
+2. Check the condition `i < 5`
+3. If `true` -- execute the loop body `alert(i)`, and then `i++`
+
+The increment `i++` is separated from the condition check (2). That's just another statement.
+
+The value returned by the increment is not used here, so there's no difference between `i++` and `++i`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/3-which-value-for/task.md b/1-js/02-first-steps/13-while-for/3-which-value-for/task.md
index df6d7a6f5b..4077641c6a 100644
--- a/1-js/02-first-steps/13-while-for/3-which-value-for/task.md
+++ b/1-js/02-first-steps/13-while-for/3-which-value-for/task.md
@@ -2,6 +2,7 @@ importance: 4
---
+<<<<<<< HEAD
# どの値が "for" ループによって表示されますか?
各ループでどの値が表示されるか書き留めてください。そして答えと比較してください。
@@ -9,11 +10,24 @@ importance: 4
両ループ同じ値を `alert` しますか?それとも違いますか?
1. ポストフィックス形式:
+=======
+# Which values get shown by the "for" loop?
+
+For each loop write down which values it is going to show. Then compare with the answer.
+
+Both loops `alert` same values or not?
+
+1. The postfix form:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
for (let i = 0; i < 5; i++) alert( i );
```
+<<<<<<< HEAD
2. プレフィックス形式:
+=======
+2. The prefix form:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
for (let i = 0; i < 5; ++i) alert( i );
diff --git a/1-js/02-first-steps/13-while-for/4-for-even/solution.md b/1-js/02-first-steps/13-while-for/4-for-even/solution.md
index 3650508ef5..fd552fbccf 100644
--- a/1-js/02-first-steps/13-while-for/4-for-even/solution.md
+++ b/1-js/02-first-steps/13-while-for/4-for-even/solution.md
@@ -8,4 +8,8 @@ for (let i = 2; i <= 10; i++) {
}
```
+<<<<<<< HEAD
ここでは、残りを取得するための "剰余" 演算子 `%` を使って偶数のチェックをしています。
+=======
+We use the "modulo" operator `%` to get the remainder and check for the evenness here.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/4-for-even/task.md b/1-js/02-first-steps/13-while-for/4-for-even/task.md
index b66becb112..cd1e89bcb4 100644
--- a/1-js/02-first-steps/13-while-for/4-for-even/task.md
+++ b/1-js/02-first-steps/13-while-for/4-for-even/task.md
@@ -2,8 +2,14 @@ importance: 5
---
+<<<<<<< HEAD
# ループで偶数を出力する
`for` ループを使って `2` から `10` までの偶数を出力してください。
+=======
+# Output even numbers in the loop
+
+Use the `for` loop to output even numbers from `2` to `10`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
[demo]
diff --git a/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md b/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md
index 47dc27b3f2..29c99ad059 100644
--- a/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md
+++ b/1-js/02-first-steps/13-while-for/5-replace-for-while/task.md
@@ -2,12 +2,22 @@ importance: 5
---
+<<<<<<< HEAD
# "for" を "while" で置き換える
その振る舞いを変えず(出力は同じまま)に、`for` ループから `while` にコードを書き換えてください。
+=======
+# Replace "for" with "while"
+
+Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
for (let i = 0; i < 3; i++) {
alert( `number ${i}!` );
}
```
+<<<<<<< HEAD
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md
index a3b82c3051..82d258f0b2 100644
--- a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md
+++ b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/solution.md
@@ -7,9 +7,18 @@ do {
} while (num <= 100 && num);
```
+<<<<<<< HEAD
ループ `do..while` は両方のチェックが真になるまで繰り返します。:
1. `num <= 100` のチェック -- つまり、入力値がまだ `100` よりも大きくない。
2. `&& num` チェックは、`num` が `null` または空文字の場合に false です。そのとき、`while` ループも停止します。
P.S. `num`が `null` の場合、`num <= 100` は `true` なので、2回目のチェックがなければ、ユーザーがCANCELをクリックするとループは止まらなくなります。 両方のチェックが必要です。
+=======
+The loop `do..while` repeats while both checks are truthy:
+
+1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`.
+2. The check `&& num` is false when `num` is `null` or an empty string. Then the `while` loop stops too.
+
+P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md
index 94e8841649..3115a862fb 100644
--- a/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md
+++ b/1-js/02-first-steps/13-while-for/6-repeat-until-correct/task.md
@@ -2,6 +2,7 @@ importance: 5
---
+<<<<<<< HEAD
# 正しい値が入力されるまで繰り返す
`100` より大きい数値を入力するプロンプトを書いてください。もし訪問者が別の数値を入力したら -- 再度、入力を促します。
@@ -9,5 +10,14 @@ importance: 5
ループは、訪問者が `100` より大きい値を入力するか、入力をキャンセル/空行の入力をするまで訪ねます。
ここでは、訪問者は数値のみを入力すると仮定します。このタスクでは、非数値に対する特別な処理を実装する必要はありません。
+=======
+# Repeat until the input is correct
+
+Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again.
+
+The loop must ask for a number until either the visitor enters a number greater than `100` or cancels the input/enters an empty line.
+
+Here we can assume that the visitor only inputs numbers. There's no need to implement a special handling for a non-numeric input in this task.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
[demo]
diff --git a/1-js/02-first-steps/13-while-for/7-list-primes/solution.md b/1-js/02-first-steps/13-while-for/7-list-primes/solution.md
index 985de98382..755126848b 100644
--- a/1-js/02-first-steps/13-while-for/7-list-primes/solution.md
+++ b/1-js/02-first-steps/13-while-for/7-list-primes/solution.md
@@ -1,6 +1,12 @@
+<<<<<<< HEAD
このタスクを解決するのに、多くのアルゴリズムがあります。
入れ子ループを使ってみましょう:
+=======
+There are many algorithms for this task.
+
+Let's use a nested loop:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
For each i in the interval {
@@ -10,7 +16,11 @@ For each i in the interval {
}
```
+<<<<<<< HEAD
ラベルを使ったコードです。:
+=======
+The code using a label:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let n = 10;
@@ -26,4 +36,8 @@ for (let i = 2; i <= n; i++) { // for each i...
}
```
+<<<<<<< HEAD
ここには最適化の余地が沢山あります。例えば、`2` から `i` の平方根までの約数を探すことができます。しかし、とにかく、私たちが大きな間隔に対して効率的になりたいなら、アプローチを変更し、高度な数学と[Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve)などの複雑なアルゴリズムに頼る必要があります。
+=======
+There's a lot of space to optimize it. For instance, we could look for the divisors from `2` to square root of `i`. But anyway, if we want to be really efficient for large intervals, we need to change the approach and rely on advanced maths and complex algorithms like [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve) etc.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/7-list-primes/task.md b/1-js/02-first-steps/13-while-for/7-list-primes/task.md
index cccb621837..2e20da222a 100644
--- a/1-js/02-first-steps/13-while-for/7-list-primes/task.md
+++ b/1-js/02-first-steps/13-while-for/7-list-primes/task.md
@@ -2,6 +2,7 @@ importance: 3
---
+<<<<<<< HEAD
# 素数の出力
`1` よりも大きい整数で、`1` と自身以外では、余りなく割ることができない場合、その数値は [素数(prime)](https://ja.wikipedia.org/wiki/%E7%B4%A0%E6%95%B0) と呼ばれます。
@@ -15,3 +16,18 @@ importance: 3
`n = 10` の場合、結果は `2,3,5,7` です。
P.S. コードは任意の `n` で動作させてください。固定値でハードコードはしないでください。
+=======
+# Output prime numbers
+
+An integer number greater than `1` is called a [prime](https://en.wikipedia.org/wiki/Prime_number) if it cannot be divided without a remainder by anything except `1` and itself.
+
+In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`.
+
+For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`.
+
+**Write the code which outputs prime numbers in the interval from `2` to `n`.**
+
+For `n = 10` the result will be `2,3,5,7`.
+
+P.S. The code should work for any `n`, not be hard-tuned for any fixed value.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/13-while-for/article.md b/1-js/02-first-steps/13-while-for/article.md
index 292f02a55d..133c860fb6 100644
--- a/1-js/02-first-steps/13-while-for/article.md
+++ b/1-js/02-first-steps/13-while-for/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# ループ: while と for
繰り返し処理は頻繁に必要になります。
@@ -22,10 +23,37 @@
## "while" ループ
`while` ループは次の構文になります:
+=======
+# Loops: while and for
+
+We often need to repeat actions.
+
+For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10.
+
+*Loops* are a way to repeat the same code multiple times.
+
+```smart header="The for..of and for..in loops"
+A small announcement for advanced readers.
+
+This article covers only basic loops: `while`, `do..while` and `for(..;..;..)`.
+
+If you came to this article searching for other types of loops, here are the pointers:
+
+- See [for..in](info:object#forin) to loop over object properties.
+- See [for..of](info:array#loops) and [iterables](info:iterable) for looping over arrays and iterable objects.
+
+Otherwise, please read on.
+```
+
+## The "while" loop
+
+The `while` loop has the following syntax:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
while (condition) {
// code
+<<<<<<< HEAD
// いわゆる "ループ本体" です
}
```
@@ -37,11 +65,25 @@ while (condition) {
```js run
let i = 0;
while (i < 3) { // 0, 次に 1, 次に 2 を表示
+=======
+ // so-called "loop body"
+}
+```
+
+While the `condition` is truthy, the `code` from the loop body is executed.
+
+For instance, the loop below outputs `i` while `i < 3`:
+
+```js run
+let i = 0;
+while (i < 3) { // shows 0, then 1, then 2
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( i );
i++;
}
```
+<<<<<<< HEAD
ループ本体の1回の実行は *イテレーション* と呼ばれます。上の例のループは3回イテレーションします。
もしも上の例に `i++` がない場合、ループは (理論上は) 永遠に繰り返されます。実際には、ブラウザはこのようなループを止める方法を提供しており、サーバサイドJavaScriptではそのプロセスを殺すことができます。
@@ -49,19 +91,37 @@ while (i < 3) { // 0, 次に 1, 次に 2 を表示
比較に限らず、どんな式や変数もループの条件にすることができます。条件は `while` によって評価され、真偽値に変換されます。
たとえば、`while (i != 0)` をより短く書く方法として`while (i)`があります:
+=======
+A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations.
+
+If `i++` was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.
+
+Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by `while`.
+
+For instance, a shorter way to write `while (i != 0)` is `while (i)`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 3;
*!*
+<<<<<<< HEAD
while (i) { // i が 0 になったとき、条件が偽になり、ループが止まります
+=======
+while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert( i );
i--;
}
```
+<<<<<<< HEAD
````smart header="本体が1行の場合、括弧は必須ではありません"
ループの本体が単一の文である場合、括弧`{…}`を省略することができます:
+=======
+````smart header="Curly braces are not required for a single-line body"
+If the loop body has a single statement, we can omit the curly braces `{…}`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 3;
@@ -71,9 +131,15 @@ while (i) alert(i--);
```
````
+<<<<<<< HEAD
## "do..while" ループ
`do..while` 構文を使うことで、条件チェックをループ本体の *下に* 移動させることができます。:
+=======
+## The "do..while" loop
+
+The condition check can be moved *below* the loop body using the `do..while` syntax:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
do {
@@ -81,9 +147,15 @@ do {
} while (condition);
```
+<<<<<<< HEAD
ループは最初に本体を実行した後、条件をチェックし、条件が真である間、本体の実行を繰り返します。
例:
+=======
+The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 0;
@@ -93,6 +165,7 @@ do {
} while (i < 3);
```
+<<<<<<< HEAD
この構文の形式は、条件が真になるかどうかに関わらず、**少なくとも1度** はループ本体を実行したい場合にのみ使用されるべきです。通常は他の形式が好まれます: `while(…) {…}`
## "for" ループ
@@ -100,6 +173,15 @@ do {
`for` ループは最も使われるものの1つです。
このようになります:
+=======
+This form of syntax should only be used when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`.
+
+## The "for" loop
+
+The `for` loop is more complex, but it's also the most commonly used loop.
+
+It looks like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
for (begin; condition; step) {
@@ -107,14 +189,22 @@ for (begin; condition; step) {
}
```
+<<<<<<< HEAD
例でこれらのパーツの意味を学びましょう。下のループは `i` が `0` から `3` になるまで(`3` は含みません)、 `alert(i)` を実行します。:
```js run
for (let i = 0; i < 3; i++) { // 0, 次に 1, 次に 2 を表示
+=======
+Let's learn the meaning of these parts by example. The loop below runs `alert(i)` for `i` from `0` up to (but not including) `3`:
+
+```js run
+for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(i);
}
```
+<<<<<<< HEAD
`for` 文を部分的に調べてみましょう:
| パート | | |
@@ -139,10 +229,37 @@ begin を実行
もしループに慣れていない場合は、上の例に戻って、紙の上でステップ毎にどのように動作するかを再現してみると理解しやすいでしょう。
これが今のケースで正確に起こっていることです:
+=======
+Let's examine the `for` statement part-by-part:
+
+| part | | |
+|-------|----------|----------------------------------------------------------------------------|
+| begin | `let i = 0` | Executes once upon entering the loop. |
+| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. |
+| 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)
+→ (if condition → run body and run step)
+→ (if condition → run body and run step)
+→ ...
+```
+
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// for (let i = 0; i < 3; i++) alert(i)
+<<<<<<< HEAD
// begin を実行
let i = 0
// if condition → body を実行し step を実行
@@ -156,19 +273,42 @@ if (i < 3) { alert(i); i++ }
````smart header="インライン変数宣言"
ここで "カウンタ" 変数 `i` はループの中で正しく宣言されます。それは "インライン" 変数宣言と呼ばれます。このような変数はループの中でだけ見えます。
+=======
+// run begin
+let i = 0
+// if condition → run body and run step
+if (i < 3) { alert(i); i++ }
+// if condition → run body and run step
+if (i < 3) { alert(i); i++ }
+// if condition → run body and run step
+if (i < 3) { alert(i); i++ }
+// ...finish, because now i == 3
+```
+
+````smart header="Inline variable declaration"
+Here, the "counter" variable `i` is declared right in the loop. This is called an "inline" variable declaration. Such variables are visible only inside the loop.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
for (*!*let*/!* i = 0; i < 3; i++) {
alert(i); // 0, 1, 2
}
+<<<<<<< HEAD
alert(i); // エラー, そのような変数はありません
```
変数を宣言する代わりに、既存のものを使うこともできます:
+=======
+alert(i); // error, no such variable
+```
+
+Instead of defining a variable, we could use an existing one:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 0;
+<<<<<<< HEAD
for (i = 0; i < 3; i++) { // 既存の変数を使用
alert(i); // 0, 1, 2
}
@@ -189,11 +329,37 @@ alert(i); // 3, ループの外で宣言されているので見える
let i = 0; // すでに i を宣言し代入済み
for (; i < 3; i++) { // "begin" 不要
+=======
+for (i = 0; i < 3; i++) { // use an existing variable
+ alert(i); // 0, 1, 2
+}
+
+alert(i); // 3, visible, because declared outside of the loop
+```
+````
+
+### Skipping parts
+
+Any part of `for` can be skipped.
+
+For example, we can omit `begin` if we don't need to do anything at the loop start.
+
+Like here:
+
+```js run
+let i = 0; // we have i already declared and assigned
+
+for (; i < 3; i++) { // no need for "begin"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( i ); // 0, 1, 2
}
```
+<<<<<<< HEAD
同じように `step` パートも除去することができます。:
+=======
+We can also remove the `step` part:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let i = 0;
@@ -203,6 +369,7 @@ for (; i < 3;) {
}
```
+<<<<<<< HEAD
ループは `while (i < 3)` と同じになりました。
実際にはすべてを除くこともできます。それは無限ループになります:
@@ -224,6 +391,29 @@ for (;;) {
例えば、以下のループはユーザに一連の数字を入力するよう求めますが、数字が入力されなかった場合は "中断" します。:
```js
+=======
+This makes the loop identical to `while (i < 3)`.
+
+We can actually remove everything, creating an infinite loop:
+
+```js
+for (;;) {
+ // repeats without limits
+}
+```
+
+Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error.
+
+## Breaking the loop
+
+Normally, a loop exits when its condition becomes falsy.
+
+But we can force the exit at any time using the special `break` directive.
+
+For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered:
+
+```js run
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let sum = 0;
while (true) {
@@ -240,6 +430,7 @@ while (true) {
alert( 'Sum: ' + sum );
```
+<<<<<<< HEAD
もしもユーザが空を入力、もしくは入力をキャンセルした場合、`break` ディレクティブは行 `(*)` で有効になります。それはループをすぐに停止し、ループ後の最初の行へ制御を渡します。つまり、`alert` です。
"無限ループ + 必要に応じた `break`" の組み合わせは、ループの最初や最後ではなく、途中や本体の様々な場所で条件をチェックする必要がある状況で最適です。
@@ -251,10 +442,24 @@ alert( 'Sum: ' + sum );
現在のイテレーションが完了し、次へ移動したいときに使います。
以下のループは、奇数値のみを出力するよう `continue` を使用しています:
+=======
+The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, `alert`.
+
+The combination "infinite loop + `break` as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.
+
+## Continue to the next iteration [#continue]
+
+The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
+
+We can use it if we're done with the current iteration and would like to move on to the next one.
+
+The loop below uses `continue` to output only odd values:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
for (let i = 0; i < 10; i++) {
+<<<<<<< HEAD
// true の場合、本体の残りのパートをスキップ
*!*if (i % 2 == 0) continue;*/!*
@@ -268,6 +473,21 @@ for (let i = 0; i < 10; i++) {
奇数値を表示するループはこのように書くこともできます:
```js
+=======
+ // if true, skip the remaining part of the body
+ *!*if (i % 2 == 0) continue;*/!*
+
+ alert(i); // 1, then 3, 5, 7, 9
+}
+```
+
+For even values of `i`, the `continue` directive stops executing the body and passes control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values.
+
+````smart header="The `continue` directive helps decrease nesting"
+A loop that shows odd values could look like this:
+
+```js run
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for (let i = 0; i < 10; i++) {
if (i % 2) {
@@ -277,6 +497,7 @@ for (let i = 0; i < 10; i++) {
}
```
+<<<<<<< HEAD
技術的な観点からは、これは上の例と同じです。確かに、`continue` の代わりに `if` ブロックでコードをラップするだけです。
しかし、副作用として括弧のネストが1段深くなります。`if` の中のコードが長い場合、全体の可読性が下がる可能性があります。
@@ -286,6 +507,17 @@ for (let i = 0; i < 10; i++) {
式ではない構文構造は、 三項演算子 `?` の中では使えないことに注意してください。特に、ディレクティブ `break/continue` はそこでは許可されません。
例えば、次のようなコードがあるとします:
+=======
+From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an `if` block instead of using `continue`.
+
+But as a side effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of `if` is longer than a few lines, that may decrease the overall readability.
+````
+
+````warn header="No `break/continue` to the right side of '?'"
+Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` aren't allowed there.
+
+For example, if we take this code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (i > 5) {
@@ -295,6 +527,7 @@ if (i > 5) {
}
```
+<<<<<<< HEAD
...これを、疑問符を使って書き直します:
```js no-beautify
@@ -311,6 +544,24 @@ if (i > 5) {
一度に複数のネストしたループから抜け出すことが必要となる場合があります。
例えば、下のコードでは 座標 `(i, j)` を `(0,0)` から `(2,2)` へプロンプトするよう、`i` と `j` をループします:
+=======
+...and rewrite it using a question mark:
+
+```js no-beautify
+(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here
+```
+
+...it stops working: there's a syntax error.
+
+This is just another reason not to use the question mark operator `?` instead of `if`.
+````
+
+## Labels for break/continue
+
+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 `(2,2)`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
for (let i = 0; i < 3; i++) {
@@ -319,18 +570,30 @@ for (let i = 0; i < 3; i++) {
let input = prompt(`Value at coords (${i},${j})`, '');
+<<<<<<< HEAD
// もしここで終了して下にある Done をしたい場合にはどうすればよいでしょう?
+=======
+ // what if we want to exit from here to Done (below)?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
alert('Done!');
```
+<<<<<<< HEAD
ユーザが入力をキャンセルした場合、処理をストップする方法が必要です。
`input` の後の通常の `break` は内部ループのみの終了です。それだけでは十分ではありません。ここでラベルが救いの手を差し伸べてくれます。
*ラベル* は、ループの前のコロンがついた識別子です:
+=======
+We need a way to stop the process if the user cancels the input.
+
+The ordinary `break` after `input` would only break the inner loop. That's not sufficient -- labels, come to the rescue!
+
+A *label* is an identifier with a colon before a loop:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
labelName: for (...) {
@@ -338,7 +601,11 @@ labelName: for (...) {
}
```
+<<<<<<< HEAD
ループの中の `break ` 文はラベルまで抜け出します:
+=======
+The `break ` statement in the loop below breaks out to the label:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
*!*outer:*/!* for (let i = 0; i < 3; i++) {
@@ -347,27 +614,43 @@ labelName: for (...) {
let input = prompt(`Value at coords (${i},${j})`, '');
+<<<<<<< HEAD
// 文字から文字またはキャンセルされた場合、両方のループから抜ける
if (!input) *!*break outer*/!*; // (*)
// 値に何かをする処理...
+=======
+ // if an empty string or canceled, then break out of both loops
+ if (!input) *!*break outer*/!*; // (*)
+
+ // do something with the value...
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
alert('Done!');
```
+<<<<<<< HEAD
上のコードで、`break outer` は `outer` と名付けされたラベルを上に探し、そのループを抜けます。
そのため、制御は `(*)` から `alert('Done!')` にまっすぐに進みます。
ラベルを別の行に移動させることもできます:
+=======
+In the code above, `break outer` looks upwards for the label named `outer` and breaks out of that loop.
+
+So the control goes straight from `(*)` to `alert('Done!')`.
+
+We can also move the label onto a separate line:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
outer:
for (let i = 0; i < 3; i++) { ... }
```
+<<<<<<< HEAD
`continue` ディレクティブもラベルと一緒に使うことができます。このケースでは、実行はラベル付けされたループの次のイテレーションにジャンプします。
````warn header="ラベルはどこにでも \"ジャンプ\" を許可するものではありません"
@@ -377,11 +660,27 @@ for (let i = 0; i < 3; i++) { ... }
```js
break label; // 以下のラベルにジャンプはしません
+=======
+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 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; // jump to the label below (doesn't work)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
label: for (...)
```
+<<<<<<< HEAD
`break` ディレクティブはコードブロックの中にある必要があります。技術的には任意のラベル付けされたコードブロックであれば機能します。
+=======
+A `break` directive must be inside a code block. Technically, any labelled code block will do, e.g.:
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
label: {
// ...
@@ -390,6 +689,7 @@ label: {
}
```
+<<<<<<< HEAD
...ですが、`break` が利用される 99.9% は上の例で見てきたように、ループの内側です。
`continue` はループの内側でのみ利用可能です。
@@ -408,3 +708,23 @@ label: {
もしも現在のイテレーションで何もしたくなく、次のイテレーションに進みたい場合は、`continue` ディレクティブを使います。
`break/continue` はループの前のラベルをサポートします。ラベルは、 `break/continue` でネストされたループを抜けて外側のループに行くための唯一の方法です。
+=======
+...Although, 99.9% of the time `break` is used inside loops, as we've seen in the examples above.
+
+A `continue` is only possible from inside a loop.
+````
+
+## Summary
+
+We covered 3 types of loops:
+
+- `while` -- The condition is checked before each iteration.
+- `do..while` -- The condition is checked after each iteration.
+- `for (;;)` -- The condition is checked before each iteration, additional settings available.
+
+To make an "infinite" loop, usually the `while(true)` construct is used. Such a loop, just like any other, can be stopped with the `break` directive.
+
+If we don't want to do anything in the current iteration and would like to forward to the next one, we can use the `continue` directive.
+
+`break/continue` support labels before the loop. A label is the only way for `break/continue` to escape a nested loop to go to an outer one.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solution.md b/1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solution.md
index b195ae6773..28b4fa51d9 100644
--- a/1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solution.md
+++ b/1-js/02-first-steps/14-switch/1-rewrite-switch-if-else/solution.md
@@ -1,6 +1,12 @@
+<<<<<<< HEAD
`switch` の機能に正確にマッチさせるためには、`if` は厳密な比較 `'==='` を使わなければなりません。
が、与えられた文字列に対しては、単純な `'=='` も使えます。
+=======
+To precisely match the functionality of `switch`, the `if` must use a strict comparison `'==='`.
+
+For given strings though, a simple `'=='` works too.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
if(browser == 'Edge') {
@@ -15,6 +21,12 @@ if(browser == 'Edge') {
}
```
+<<<<<<< HEAD
注意してください: 構造 `browser == 'Chrome' || browser == 'Firefox' …` はより良い可読性のために複数行に分割されています。
しかし、`switch` 構造は以前としてより洗練されており、説明的です。
+=======
+Please note: the construct `browser == 'Chrome' || browser == 'Firefox' …` is split into multiple lines for better readability.
+
+But the `switch` construct is still cleaner and more descriptive.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md b/1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
index 014b3ab83a..a54a188934 100644
--- a/1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
+++ b/1-js/02-first-steps/14-switch/2-rewrite-if-switch/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
最初の2つのチェックは2つの `case` になります。3つ目のチェックは2つのケースに分割されます。:
+=======
+The first two checks turn into two `case`. The third check is split into two cases:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = +prompt('a?', '');
@@ -21,6 +25,12 @@ switch (a) {
}
```
+<<<<<<< HEAD
注意してください: 末尾の `break` は必須ではありませんが、将来のためにそれを置く方がよいです。
将来、たとえば `case 4` のような `case` を追加したい機会があります。そして、以前に break を置くのを忘れていた場合、 `case 3` の終わりでエラーが発生します。なので、これは一種の自己保険です。
+=======
+Please note: the `break` at the bottom is not required. But we put it to make the code future-proof.
+
+In the future, there is a chance that we'd want to add one more `case`, for example `case 4`. And if we forget to add a break before it, at the end of `case 3`, there will be an error. So that's a kind of self-insurance.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/14-switch/article.md b/1-js/02-first-steps/14-switch/article.md
index 90e485b2eb..f1786a4958 100644
--- a/1-js/02-first-steps/14-switch/article.md
+++ b/1-js/02-first-steps/14-switch/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# switch文
`switch` 文は複数の `if` チェックに置換できます。
@@ -9,6 +10,19 @@
`switch` は1つ以上の `case` ブロックを持ち、 オプションで default を持ちます。
このようになります:
+=======
+# The "switch" statement
+
+A `switch` statement can replace multiple `if` checks.
+
+It gives a more descriptive way to compare a value with multiple variants.
+
+## The syntax
+
+The `switch` has one or more `case` blocks and an optional default.
+
+It looks like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js no-beautify
switch(x) {
@@ -26,6 +40,7 @@ switch(x) {
}
```
+<<<<<<< HEAD
- `x` の値は、最初の `case` (それは `value1`)の値と厳密な等価のチェックをされます、そして2つ目(`value2`)と続きます。
- 等価なものが見つかった場合、 `switch` は該当する `case` から始まるコードを実行し始めます。最も近い `break` まで(もしくは `switch` の終わりまで)。
- マッチするケースが無い場合は、`default` コードが実行されます(存在する場合)
@@ -33,6 +48,15 @@ switch(x) {
## 例
`switch` の例です(実行されるコードはハイライトされています)
+=======
+- The value of `x` is checked for a strict equality to the value from the first `case` (that is, `value1`) then to the second (`value2`) and so on.
+- If the equality is found, `switch` starts to execute the code starting from the corresponding `case`, until the nearest `break` (or until the end of `switch`).
+- If no case is matched then the `default` code is executed (if it exists).
+
+## An example
+
+An example of `switch` (the executed code is highlighted):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = 2 + 2;
@@ -47,13 +71,18 @@ switch (a) {
break;
*/!*
case 5:
+<<<<<<< HEAD
alert( 'Too large' );
+=======
+ alert( 'Too big' );
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
break;
default:
alert( "I don't know such values" );
}
```
+<<<<<<< HEAD
ここで、 `switch` は、最初の `case` である `3` から `a` との比較を始めます。マッチはしません。
そして `4` です。マッチするので、`case 4` から最も近い `break` までの実行を開始します。
@@ -61,6 +90,15 @@ switch (a) {
**`break` がない場合、チェックなしで次の `case` の実行を継続します。**
`break` なしの例です:
+=======
+Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails.
+
+Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`.
+
+**If there is no `break` then the execution continues with the next `case` without any checks.**
+
+An example without `break`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = 2 + 2;
@@ -79,7 +117,11 @@ switch (a) {
}
```
+<<<<<<< HEAD
上の例では、3つの `alert` が順に実行されるでしょう。
+=======
+In the example above we'll see sequential execution of three `alert`s:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( 'Exactly!' );
@@ -87,10 +129,17 @@ alert( 'Too big' );
alert( "I don't know such values" );
```
+<<<<<<< HEAD
````smart header="どのような式も `switch / case` の引数になります"
`switch` と `case` の両方は任意の表現が可能です。
例:
+=======
+````smart header="Any expression can be a `switch/case` argument"
+Both `switch` and `case` allow arbitrary expressions.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let a = "1";
@@ -107,6 +156,7 @@ switch (+a) {
alert("this doesn't run");
}
```
+<<<<<<< HEAD
ここで `+a` は `1` が与えられ、 `case` で `b + 1` と比較されます。そして、対応するコードが実行されます。
````
@@ -118,6 +168,19 @@ switch (+a) {
```js run no-beautify
let a = 2 + 2;
+=======
+Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed.
+````
+
+## Grouping of "case"
+
+Several variants of `case` which share the same code can be grouped.
+
+For example, if we want the same code to run for `case 3` and `case 5`:
+
+```js run no-beautify
+let a = 3;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
switch (a) {
case 4:
@@ -125,7 +188,11 @@ switch (a) {
break;
*!*
+<<<<<<< HEAD
case 3: // (*) 2つのケースをグループ化
+=======
+ case 3: // (*) grouped two cases
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
@@ -137,6 +204,7 @@ switch (a) {
}
```
+<<<<<<< HEAD
今、`3` と `5` は同じメッセージを表示します。
ケースを "グループ化" する機能は、`break` がない場合の `switch/case` の動作の副作用です。ここで `case 3` の実行は、`break` がないので `(*)` の行から始まり、`case 5` を通り抜けます。
@@ -149,6 +217,20 @@ switch (a) {
```js run
let arg = prompt("Enter a value?")
+=======
+Now both `3` and `5` show the same message.
+
+The ability to "group" cases is a side effect of how `switch/case` works without `break`. Here the execution of `case 3` starts from the line `(*)` and goes through `case 5`, because there's no `break`.
+
+## Type matters
+
+Let's emphasize that the equality check is always strict. The values must be of the same type to match.
+
+For example, let's consider the code:
+
+```js run
+let arg = prompt("Enter a value?");
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
switch (arg) {
case '0':
case '1':
@@ -163,6 +245,7 @@ switch (arg) {
alert( 'Never executes!' );
break;
default:
+<<<<<<< HEAD
alert( 'An unknown value' )
}
```
@@ -170,3 +253,12 @@ switch (arg) {
1. `0`, `1` の場合、最初の `alert` が実行されます。
2. `2` の場合は2つ目の `alert` が実行されます。
3. しかし `3` の場合、`prompt` の結果は文字列の `"3"`なので、数字の `3` との厳密な等価 `===` ではありません。そのため、`case 3` はデッドコードです! `default` ケースが実行されるでしょう。
+=======
+ alert( 'An unknown value' );
+}
+```
+
+1. For `0`, `1`, the first `alert` runs.
+2. For `2` the second `alert` runs.
+3. But for `3`, the result of the `prompt` is a string `"3"`, which is not strictly equal `===` to the number `3`. So we've got a dead code in `case 3`! The `default` variant will execute.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md b/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md
index 331d318df8..6d97153a65 100644
--- a/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md
+++ b/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md
@@ -1 +1,7 @@
+<<<<<<< HEAD
違いはありません。
+=======
+No difference!
+
+In both cases, `return confirm('Did parents allow you?')` executes exactly when the `if` condition is falsy.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md b/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md
index 142efa1896..fcd86fb82c 100644
--- a/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md
+++ b/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md
@@ -2,11 +2,19 @@ importance: 4
---
+<<<<<<< HEAD
# "else" は必須ですか?
次の関数は、パラメータ `age` が `18` より大きい場合に `true` を返します。
それ以外の場合には確認を行い、その結果を返します。:
+=======
+# Is "else" required?
+
+The following function returns `true` if the parameter `age` is greater than `18`.
+
+Otherwise it asks for a confirmation and returns its result:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function checkAge(age) {
@@ -21,7 +29,11 @@ function checkAge(age) {
}
```
+<<<<<<< HEAD
もし `else` が削除された場合、この関数は違う動きになるでしょうか?
+=======
+Will the function work differently if `else` is removed?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function checkAge(age) {
@@ -35,4 +47,8 @@ function checkAge(age) {
}
```
+<<<<<<< HEAD
これら2つのバリアントの振る舞いで何か違いはあるでしょうか?
+=======
+Is there any difference in the behavior of these two variants?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md
index 0594570c72..d7411f9c7b 100644
--- a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md
+++ b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
疑問符演算子 `'?'` を利用:
+=======
+Using a question mark operator `'?'`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function checkAge(age) {
@@ -6,7 +10,11 @@ function checkAge(age) {
}
```
+<<<<<<< HEAD
OR `||` を利用(最も短いバリアント):
+=======
+Using OR `||` (the shortest variant):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function checkAge(age) {
@@ -14,4 +22,8 @@ function checkAge(age) {
}
```
+<<<<<<< HEAD
`age > 18` の周りの括弧はここでは必須ではないことに留意してください。より良い可読性のために存在しています。
+=======
+Note that the parentheses around `age > 18` are not required here. They exist for better readability.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md
index 156192196a..485ab41c55 100644
--- a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md
+++ b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md
@@ -2,26 +2,47 @@ importance: 4
---
+<<<<<<< HEAD
# '?' または '||' を使って関数を書き直す
次の関数は、パラメータ `age` が `18` より大きい場合に `true` を返します。
それ以外の場合には確認を行い、その結果を返します。:
+=======
+# Rewrite the function using '?' or '||'
+
+The following function returns `true` if the parameter `age` is greater than `18`.
+
+Otherwise it asks for a confirmation and returns its result.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function checkAge(age) {
if (age > 18) {
return true;
} else {
+<<<<<<< HEAD
return confirm('Do you have your parents permission to access this page?');
+=======
+ return confirm('Did parents allow you?');
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
それを書き直し、1行で `if` なしで同じをことを実行してください。
`checkAge` の2つのバリアントを作ってください。:
1. 疑問符演算子 `'?'` を使うケース
2. OR `||` を使うケース
+=======
+Rewrite it, to perform the same, but without `if`, in a single line.
+
+Make two variants of `checkAge`:
+
+1. Using a question mark operator `?`
+2. Using OR `||`
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/3-min/solution.md b/1-js/02-first-steps/15-function-basics/3-min/solution.md
index 3d2e41de5f..9805e0941f 100644
--- a/1-js/02-first-steps/15-function-basics/3-min/solution.md
+++ b/1-js/02-first-steps/15-function-basics/3-min/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
`if` を使った方法:
+=======
+A solution using `if`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function min(a, b) {
@@ -10,7 +14,11 @@ function min(a, b) {
}
```
+<<<<<<< HEAD
疑問符演算子 `'?'` を使った方法:
+=======
+A solution with a question mark operator `'?'`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function min(a, b) {
@@ -18,4 +26,8 @@ function min(a, b) {
}
```
+<<<<<<< HEAD
P.S. 等しい `a == b` 場合、何を返すかは気にする必要ありません。
+=======
+P.S. In the case of an equality `a == b` it does not matter what to return.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/3-min/task.md b/1-js/02-first-steps/15-function-basics/3-min/task.md
index a92bad0620..000e771f52 100644
--- a/1-js/02-first-steps/15-function-basics/3-min/task.md
+++ b/1-js/02-first-steps/15-function-basics/3-min/task.md
@@ -2,14 +2,26 @@ importance: 1
---
+<<<<<<< HEAD
# 関数 min(a, b)
2つの数値 `a` と `b` で小さい方を返す関数 `min(a,b)` を書きなさい。
例:
+=======
+# Function min(a, b)
+
+Write a function `min(a,b)` which returns the least of two numbers `a` and `b`.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
min(2, 5) == 2
min(3, -1) == -1
min(1, 1) == 1
```
+<<<<<<< HEAD
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/4-pow/solution.md b/1-js/02-first-steps/15-function-basics/4-pow/solution.md
index 79eb2b442e..19fe9011fc 100644
--- a/1-js/02-first-steps/15-function-basics/4-pow/solution.md
+++ b/1-js/02-first-steps/15-function-basics/4-pow/solution.md
@@ -13,11 +13,9 @@ function pow(x, n) {
let x = prompt("x?", '');
let n = prompt("n?", '');
-if (n <= 1) {
- alert(`Power ${n} is not supported,
- use an integer greater than 0`);
+if (n < 1) {
+ alert(`Power ${n} is not supported, use a positive integer`);
} else {
alert( pow(x, n) );
}
```
-
diff --git a/1-js/02-first-steps/15-function-basics/4-pow/task.md b/1-js/02-first-steps/15-function-basics/4-pow/task.md
index 651733fa70..37d44edfef 100644
--- a/1-js/02-first-steps/15-function-basics/4-pow/task.md
+++ b/1-js/02-first-steps/15-function-basics/4-pow/task.md
@@ -2,14 +2,21 @@ importance: 4
---
+<<<<<<< HEAD
# 関数 pow(x,n)
`x` の累乗 `n` を返す関数 `pow(x,n)` を書いてください。 つまり、 `x` をそれ自身で `n` 回掛け、その結果を返します。
+=======
+# Function pow(x,n)
+
+Write a function `pow(x,n)` that returns `x` in power `n`. Or, in other words, multiplies `x` by itself `n` times and returns the result.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
pow(3, 2) = 3 * 3 = 9
pow(3, 3) = 3 * 3 * 3 = 27
+<<<<<<< HEAD
pow(1, 100) = 1 * 1 * ...*1 = 1
```
@@ -18,3 +25,13 @@ pow(1, 100) = 1 * 1 * ...*1 = 1
[demo]
P.S. このタスクでは、`n` に自然数のみをサポートします。
+=======
+pow(1, 100) = 1 * 1 * ...* 1 = 1
+```
+
+Create a web-page that prompts for `x` and `n`, and then shows the result of `pow(x,n)`.
+
+[demo]
+
+P.S. In this task the function should support only natural values of `n`: integers up from `1`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/15-function-basics/article.md b/1-js/02-first-steps/15-function-basics/article.md
index f85034e2a8..6500e9ed45 100644
--- a/1-js/02-first-steps/15-function-basics/article.md
+++ b/1-js/02-first-steps/15-function-basics/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 関数
スクリプトの色々な場所で同じアクションを実行する必要がある場合がよくあります。
@@ -13,6 +14,23 @@
関数を作るために、*関数定義* を使います。
次のようになります:
+=======
+# Functions
+
+Quite often we need to perform a similar action in many places of the script.
+
+For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.
+
+Functions are the main "building blocks" of the program. They allow the code to be called many times without repetition.
+
+We've already seen examples of built-in functions, like `alert(message)`, `prompt(message, default)` and `confirm(question)`. But we can create functions of our own as well.
+
+## Function Declaration
+
+To create a function we can use a *function declaration*.
+
+It looks like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function showMessage() {
@@ -20,6 +38,7 @@ function showMessage() {
}
```
+<<<<<<< HEAD
`function` キーワードが最初にきて、次に *関数名* がきます、そして括弧の中に *パラメータ* のリスト(カンマ区切り、上の例では空)がきて、最後に中括弧の間に関数のコード、 "関数本体" です。
```js
@@ -31,6 +50,19 @@ function name(parameters) {
作成した関数はその関数名で呼び出すことができます: `showMessage()`
例:
+=======
+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, we'll see examples later) and finally the code of the function, also named "the function body", between curly braces.
+
+```js
+function name(parameter1, parameter2, ... parameterN) {
+ // body
+}
+```
+
+Our new function can be called by its name: `showMessage()`.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function showMessage() {
@@ -43,6 +75,7 @@ showMessage();
*/!*
```
+<<<<<<< HEAD
`showMessage()` の呼び出しは、関数のコードを実行します。この例では、2度メッセージが表示されます。
この例は関数のメインの目的の1つを明確に示しています: コードの複製を回避する、と言うことです。
@@ -54,11 +87,28 @@ showMessage();
関数内で定義された変数は、関数内でのみ参照可能です。
例:
+=======
+The call `showMessage()` executes the code of the function. Here we will see the message two times.
+
+This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.
+
+If we ever need to change the message or the way it is shown, it's enough to modify the code in one place: the function which outputs it.
+
+## Local variables
+
+A variable declared inside a function is only visible inside that function.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function showMessage() {
*!*
+<<<<<<< HEAD
let message = "Hello, I'm JavaScript!"; // ローカル変数
+=======
+ let message = "Hello, I'm JavaScript!"; // local variable
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert( message );
@@ -66,12 +116,21 @@ function showMessage() {
showMessage(); // Hello, I'm JavaScript!
+<<<<<<< HEAD
alert( message ); // <-- エラー! 変数は関数のローカルです
```
## 外部変数
関数は外部変数にアクセスすることもできます。次の例を見てください:
+=======
+alert( message ); // <-- Error! The variable is local to the function
+```
+
+## Outer variables
+
+A function can access an outer variable as well, for example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
let *!*userName*/!* = 'John';
@@ -84,20 +143,31 @@ function showMessage() {
showMessage(); // Hello, John
```
+<<<<<<< HEAD
関数は外部変数に対してフルアクセス権を持ち、変更することもできます。
例:
+=======
+The function has full access to the outer variable. It can modify it as well.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let *!*userName*/!* = 'John';
function showMessage() {
+<<<<<<< HEAD
*!*userName*/!* = "Bob"; // (1) 外部変数の変更
+=======
+ *!*userName*/!* = "Bob"; // (1) changed the outer variable
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let message = 'Hello, ' + *!*userName*/!*;
alert(message);
}
+<<<<<<< HEAD
alert( userName ); // 関数呼び出しの前は *!*John*/!*
showMessage();
@@ -108,19 +178,36 @@ alert( userName ); // *!*Bob*/!*, 関数によって値が変更されました
外部の変数は、同じ名前のローカル変数が存在しない場合にのみ使われます。そのため、`let` を忘れた場合、意図せず外部の変数を変更してしまう可能性があります。
同じ名前の変数が関数内に宣言されている場合は、外部変数を *隠します*。例えば、以下のコードでは関数はローカルの `userName` を使います。外部の `userName` は無視されます。
+=======
+alert( userName ); // *!*John*/!* before the function call
+
+showMessage();
+
+alert( userName ); // *!*Bob*/!*, the value was modified by the function
+```
+
+The outer variable is only used if there's no local one.
+
+If a same-named variable is declared inside the function then it *shadows* the outer one. For instance, in the code below the function uses the local `userName`. The outer one is ignored:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let userName = 'John';
function showMessage() {
*!*
+<<<<<<< HEAD
let userName = "Bob"; // ローカル変数の宣言
+=======
+ let userName = "Bob"; // declare a local variable
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
let message = 'Hello, ' + userName; // *!*Bob*/!*
alert(message);
}
+<<<<<<< HEAD
// 関数は作られ独自の userName を使います
showMessage();
@@ -156,12 +243,50 @@ showMessage('Ann', "What's up?"); // Ann: What's up? (**)
ここにもう1つ例があります: 私たちは変数 `from` を持っており、それを関数に渡します。注意してください:関数は常に値のコピーを取得するため、関数の中の処理は `from` を変更していますが、その変更は外には見えません:
+=======
+// the function will create and use its own userName
+showMessage();
+
+alert( userName ); // *!*John*/!*, unchanged, the function did not access the outer variable
+```
+
+```smart header="Global variables"
+Variables declared outside of any function, such as the outer `userName` in the code above, are called *global*.
+
+Global variables are visible from any function (unless shadowed by locals).
+
+It's a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data.
+```
+
+## Parameters
+
+We can pass arbitrary data to functions using parameters.
+
+In the example below, the function has two parameters: `from` and `text`.
+
+```js run
+function showMessage(*!*from, text*/!*) { // parameters: from, text
+ alert(from + ': ' + text);
+}
+
+*!*showMessage('Ann', 'Hello!');*/!* // Ann: Hello! (*)
+*!*showMessage('Ann', "What's up?");*/!* // Ann: What's up? (**)
+```
+
+When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them.
+
+Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function showMessage(from, text) {
*!*
+<<<<<<< HEAD
from = '*' + from + '*'; // "from" をより良く見せる
+=======
+ from = '*' + from + '*'; // make "from" look nicer
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert( from + ': ' + text );
@@ -171,6 +296,7 @@ let from = "Ann";
showMessage(from, "Hello"); // *Ann*: Hello
+<<<<<<< HEAD
// "from" の値は同じで、関数はローカルコピーを変更しています。
alert( from ); // Ann
```
@@ -190,14 +316,43 @@ alert( from ); // Ann
関数の呼び出し時に引数が与えられていない場合、対応する値は `undefined` になります。
例えば、前述の関数 `showMessage(from, text)` は1つの引数で呼ぶことも出来ます:
+=======
+// the value of "from" is the same, the function modified a local copy
+alert( from ); // Ann
+```
+
+When a value is passed as a function parameter, it's also called an *argument*.
+
+In other words, to put these terms straight:
+
+- A parameter is the variable listed inside the parentheses in the function declaration (it's a declaration time term).
+- An argument is the value that is passed to the function when it is called (it's a call time term).
+
+We declare functions listing their parameters, then call them passing arguments.
+
+In the example above, one might say: "the function `showMessage` is declared with two parameters, then called with two arguments: `from` and `"Hello"`".
+
+
+## Default values
+
+If a function is called, but an argument is not provided, then the corresponding value becomes `undefined`.
+
+For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
showMessage("Ann");
```
+<<<<<<< HEAD
それはエラーではありません。このような呼び出しは `"*Ann*: undefined"` を出力します。`text` が渡されていないため、`text` は `undefined` となります。
パラメータのいわゆる "デフォルト" (呼び出し時に省略された場合に使用される)値を、関数宣言の中で `=` を使用して指定することが可能です:
+=======
+That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`.
+
+We can specify the so-called "default" (to use if omitted) value for a parameter in the function declaration, using `=`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function showMessage(from, *!*text = "no text given"*/!*) {
@@ -207,6 +362,7 @@ function showMessage(from, *!*text = "no text given"*/!*) {
showMessage("Ann"); // Ann: no text given
```
+<<<<<<< HEAD
これで `text` パラメータが渡されていない場合、 値は `"no text given"` になります。
ここで、 `"no text given"` は文字列ですが、より複雑な式にすることもできます。そしてそれはパラメータが無い場合にのみ評価され、代入されます。なので、このようなことも可能です:
@@ -234,6 +390,77 @@ JavaScriptでは、デフォルト値はそれぞれのパラメータが与え
function showMessage(text) {
*!*
if (text === undefined) {
+=======
+Now if the `text` parameter is not passed, it will get the value `"no text given"`.
+
+The default value also jumps in if the parameter exists, but strictly equals `undefined`, like this:
+
+```js
+showMessage("Ann", undefined); // Ann: no text given
+```
+
+Here `"no text given"` is a string, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. So, this is also possible:
+
+```js run
+function showMessage(from, text = anotherFunction()) {
+ // anotherFunction() only executed if no text given
+ // its result becomes the value of text
+}
+```
+
+```smart header="Evaluation of default parameters"
+In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.
+
+In the example above, `anotherFunction()` isn't called at all, if the `text` parameter is provided.
+
+On the other hand, it's independently called every time when `text` is missing.
+```
+
+````smart header="Default parameters in old JavaScript code"
+Several years ago, JavaScript didn't support the syntax for default parameters. So people used other ways to specify them.
+
+Nowadays, we can come across them in old scripts.
+
+For example, an explicit check for `undefined`:
+
+```js
+function showMessage(from, text) {
+*!*
+ if (text === undefined) {
+ text = 'no text given';
+ }
+*/!*
+
+ alert( from + ": " + text );
+}
+```
+
+...Or using the `||` operator:
+
+```js
+function showMessage(from, text) {
+ // If the value of text is falsy, assign the default value
+ // this assumes that text == "" is the same as no text at all
+ text = text || 'no text given';
+ ...
+}
+```
+````
+
+
+### Alternative default parameters
+
+Sometimes it makes sense to assign default values for parameters at a later stage after the function declaration.
+
+We can check if the parameter is passed during the function execution, by comparing it with `undefined`:
+
+```js run
+function showMessage(text) {
+ // ...
+
+*!*
+ if (text === undefined) { // if the parameter is missing
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
text = 'empty message';
}
*/!*
@@ -244,21 +471,37 @@ function showMessage(text) {
showMessage(); // empty message
```
+<<<<<<< HEAD
...もしくは `||` 演算子:
```js
// パラメータが省略 or "" の場合, 'empty' を設定
function showMessage(text) {
+=======
+...Or we could use the `||` operator:
+
+```js
+function showMessage(text) {
+ // if text is undefined or otherwise falsy, set it to 'empty'
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
text = text || 'empty';
...
}
```
+<<<<<<< HEAD
モダンな JavaScript エンジンは [NULL合体演算子](info:nullish-coalescing-operator) `??` をサポートしており、`0` などの偽値を通常とみなす場合に適しています:
```js run
// count パラメータがない場合は "unknown"
function showCount(count) {
+=======
+Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when most falsy values, such as `0`, should be considered "normal":
+
+```js run
+function showCount(count) {
+ // if count is undefined or null, show "unknown"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(count ?? "unknown");
}
@@ -267,11 +510,19 @@ showCount(null); // unknown
showCount(); // unknown
```
+<<<<<<< HEAD
## 値の返却
関数は、実行結果として呼び出しコードに値を戻すことが出来ます。
最もシンプルな例は2つの値の合計を行う関数です:
+=======
+## Returning a value
+
+A function can return a value back into the calling code as the result.
+
+The simplest example would be a function that sums two values:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
function sum(a, b) {
@@ -282,6 +533,7 @@ let result = sum(1, 2);
alert( result ); // 3
```
+<<<<<<< HEAD
ディレクティブ `return` は関数の任意の場所に置くことが出来ます。もしも実行がそこに到達したとき、関数は停止し、値を呼び出し元のコードに返します(上の `result` へ代入します)。
1つの関数に多くの `return` が出現することもあります。例えば:
@@ -289,12 +541,25 @@ alert( result ); // 3
```js run
function checkAge(age) {
if (age > 18) {
+=======
+The directive `return` can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to `result` above).
+
+There may be many occurrences of `return` in a single function. For instance:
+
+```js run
+function checkAge(age) {
+ if (age >= 18) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
return true;
*/!*
} else {
*!*
+<<<<<<< HEAD
return confirm('Got a permission from the parents?');
+=======
+ return confirm('Do you have permission from your parents?');
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
}
@@ -308,9 +573,15 @@ if ( checkAge(age) ) {
}
```
+<<<<<<< HEAD
値なしで `return` を使うことも出来ます。これは関数を直ぐに終了させます。
例:
+=======
+It is possible to use `return` without a value. That causes the function to exit immediately.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function showMovie(age) {
@@ -325,10 +596,17 @@ function showMovie(age) {
}
```
+<<<<<<< HEAD
上のコードでは、`checkAge(age)` が `false` を返すと、`showMovie` は `alert` の処理をしません。
````smart header="空の `return`、 または返却がないものは `undefined` を返します"
関数が値を返却しない場合、それは `undefined` を返却した場合と同じになります。:
+=======
+In the code above, if `checkAge(age)` returns `false`, then `showMovie` won't proceed to the `alert`.
+
+````smart header="A function with an empty `return` or without it returns `undefined`"
+If a function does not return a value, it is the same as if it returns `undefined`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function doNothing() { /* empty */ }
@@ -336,7 +614,11 @@ function doNothing() { /* empty */ }
alert( doNothing() === undefined ); // true
```
+<<<<<<< HEAD
空の `return` もまた `return undefined` と同じです:
+=======
+An empty `return` is also the same as `return undefined`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function doNothing() {
@@ -347,23 +629,38 @@ alert( doNothing() === undefined ); // true
```
````
+<<<<<<< HEAD
````warn header="`return`と値の間に改行を入れないでください"
`return` が長い式の場合、このように別の行に書くのが魅力的に見えるかもしれません:
+=======
+````warn header="Never add a newline between `return` and the value"
+For a long expression in `return`, it might be tempting to put it on a separate line, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
return
(some + long + expression + or + whatever * f(a) + f(b))
```
+<<<<<<< HEAD
JavaScriptは `return` の後にセミコロンを想定するため、これは動作しません。これは次と同じように動作します:
+=======
+That doesn't work, because JavaScript assumes a semicolon after `return`. That'll work the same as:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
return*!*;*/!*
(some + long + expression + or + whatever * f(a) + f(b))
```
+<<<<<<< HEAD
従って、これは事実上空の返却になります。なので、値は同じ行に置く必要があります。
もし複数行にまたがった式を返却したい場合は、`return` と同じ行から開始する必要があります。あるいは、少なくとも次のように開始括弧を置きます:
+=======
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
return (
@@ -372,6 +669,7 @@ return (
whatever * f(a) + f(b)
)
```
+<<<<<<< HEAD
これは期待する通りに動作するでしょう。
````
@@ -433,6 +731,69 @@ checkPermission(..) // 権限をチェックし、true/false を返します
例えば、下にある2つの関数 `showPrimes(n)`を比べてみましょう。どちらも[素数](https://en.wikipedia.org/wiki/Prime_number)を `n` に達するまで出力します。
1つ目のパターンはラベルを使います:
+=======
+And it will work just as we expect it to.
+````
+
+## Naming a function [#function-naming]
+
+Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets an indication of what the function does.
+
+It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an agreement within the team on the meaning of the prefixes.
+
+For instance, functions that start with `"show"` usually show something.
+
+Function starting with...
+
+- `"get…"` -- return a value,
+- `"calc…"` -- calculate something,
+- `"create…"` -- create something,
+- `"check…"` -- check something and return a boolean, etc.
+
+Examples of such names:
+
+```js no-beautify
+showMessage(..) // shows a message
+getAge(..) // returns the age (gets it somehow)
+calcSum(..) // calculates a sum and returns the result
+createForm(..) // creates a form (and usually returns it)
+checkPermission(..) // checks a permission, returns true/false
+```
+
+With prefixes in place, a glance at a function name gives an understanding what kind of work it does and what kind of value it returns.
+
+```smart header="One function -- one action"
+A function should do exactly what is suggested by its name, no more.
+
+Two independent actions usually deserve two functions, even if they are usually called together (in that case we can make a 3rd function that calls those two).
+
+A few examples of breaking this rule:
+
+- `getAge` -- would be bad if it shows an `alert` with the age (should only get).
+- `createForm` -- would be bad if it modifies the document, adding a form to it (should only create it and return).
+- `checkPermission` -- would be bad if it displays the `access granted/denied` message (should only perform the check and return the result).
+
+These examples assume common meanings of prefixes. You and your team are free to agree on other meanings, but usually they're not much different. In any case, you should have a firm understanding of what a prefix means, what a prefixed function can and cannot do. All same-prefixed functions should obey the rules. And the team should share the knowledge.
+```
+
+```smart header="Ultrashort function names"
+Functions that are used *very often* sometimes have ultrashort names.
+
+For example, the [jQuery](https://jquery.com/) framework defines a function with `$`. The [Lodash](https://lodash.com/) library has its core function named `_`.
+
+These are exceptions. Generally function names should be concise and descriptive.
+```
+
+## Functions == Comments
+
+Functions should be short and do exactly one thing. If that thing is big, maybe it's worth it to split the function into a few smaller functions. Sometimes following this rule may not be that easy, but it's definitely a good thing.
+
+A separate function is not only easier to test and debug -- its very existence is a great comment!
+
+For instance, compare the two functions `showPrimes(n)` below. Each one outputs [prime numbers](https://en.wikipedia.org/wiki/Prime_number) up to `n`.
+
+The first variant uses a label:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function showPrimes(n) {
@@ -447,7 +808,11 @@ function showPrimes(n) {
}
```
+<<<<<<< HEAD
2つ目のパターンは、素数の確認をするための追加の関数 `isPrime(n)` を使います。
+=======
+The second variant uses an additional function `isPrime(n)` to test for primality:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function showPrimes(n) {
@@ -467,6 +832,7 @@ function isPrime(n) {
}
```
+<<<<<<< HEAD
2つ目のパターンのほうが理解しやすいですね。コードの塊の代わりに、アクション(`isPrime`) の名前を見ます。このようなコードは *自己記述的* と呼ばれる場合があります。
従って、関数はその再利用を意図していない場合でも作ることがあります。それらはコードを構造化し、読みやすくします。
@@ -474,6 +840,15 @@ function isPrime(n) {
## サマリ
関数はこのように定義します:
+=======
+The second variant is easier to understand, isn't it? Instead of the code piece we see a name of the action (`isPrime`). Sometimes people refer to such code as *self-describing*.
+
+So, functions can be created even if we don't intend to reuse them. They structure the code and make it readable.
+
+## Summary
+
+A function declaration looks like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function name(parameters, delimited, by, comma) {
@@ -481,6 +856,7 @@ function name(parameters, delimited, by, comma) {
}
```
+<<<<<<< HEAD
- パラメータとして関数に渡される値は、ローカル変数にコピーされます。
- 関数は外部の変数にアクセスすることができます。しかし、それは内側からのみ機能します。関数の外側のコードは、関数のローカル変数を見ることはできません。
- 関数は値を返すことができます。もしもそれをしなかった場合、戻り値は `undefined` です。
@@ -496,3 +872,20 @@ function name(parameters, delimited, by, comma) {
- `create…`, `show…`, `get…`, `check…` など、数多くのよく知られた関数のプレフィックスが存在します。関数がすることのヒントとしてそれらを使いましょう。
関数はスクリプトの主な構成要素です。今や私たちは基礎をカバーしたので、実際にそれらを作り使い始めることができます。しかし、それはまだほんの始まりに過ぎません。私たちは何度もそれらに戻り、より高度な機能について深めていきます。
+=======
+- Values passed to a function as parameters are copied to its local variables.
+- A function may access outer variables. But it works only from inside out. The code outside of the function doesn't see its local variables.
+- A function can return a value. If it doesn't, then its result is `undefined`.
+
+To make the code clean and easy to understand, it's recommended to use mainly local variables and parameters in the function, not outer variables.
+
+It is always easier to understand a function which gets parameters, works with them and returns a result than a function which gets no parameters, but modifies outer variables as a side effect.
+
+Function naming:
+
+- A name should clearly describe what the function does. When we see a function call in the code, a good name instantly gives us an understanding what it does and returns.
+- A function is an action, so function names are usually verbal.
+- There exist many well-known function prefixes like `create…`, `show…`, `get…`, `check…` and so on. Use them to hint what a function does.
+
+Functions are the main building blocks of scripts. Now we've covered the basics, so we actually can start creating and using them. But that's only the beginning of the path. We are going to return to them many times, going more deeply into their advanced features.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/16-function-expressions/article.md b/1-js/02-first-steps/16-function-expressions/article.md
index 8537f038eb..07f9b126df 100644
--- a/1-js/02-first-steps/16-function-expressions/article.md
+++ b/1-js/02-first-steps/16-function-expressions/article.md
@@ -1,8 +1,16 @@
+<<<<<<< HEAD
# 関数式
JavaScriptでは、関数は "魔法の言語構造" ではなく、特別な種類の値です。
前に私たちが使っていた構文は *関数宣言* と呼ばれます:
+=======
+# Function expressions
+
+In JavaScript, a function is not a "magical language structure", but a special kind of value.
+
+The syntax that we used before is called a *Function Declaration*:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function sayHi() {
@@ -10,9 +18,17 @@ function sayHi() {
}
```
+<<<<<<< HEAD
これとは別に、*関数式* と呼ばれる、関数を作るための別の構文があります。
それはこのようになります:
+=======
+There is another syntax for creating a function that is called a *Function Expression*.
+
+It allows us to create a new function in the middle of any expression.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let sayHi = function() {
@@ -20,11 +36,29 @@ let sayHi = function() {
};
```
+<<<<<<< HEAD
ここでは、関数は他の任意の値と同じように明示的に変数に代入されています。どのように関数が定義されても、それは単に変数 `sayHi` に格納される値です。
これらのコード例の意味は同じです: "関数を作成し、変数 `sayHi` にそれを格納します"
`alert` を使ってその値を出力することもできます:
+=======
+Here we can see a variable `sayHi` getting a value, the new function, created as `function() { alert("Hello"); }`.
+
+As the function creation happens in the context of the assignment expression (to the right side of `=`), this is a *Function Expression*.
+
+Please note, there's no name after the `function` keyword. Omitting a name is allowed for Function Expressions.
+
+Here we immediately assign it to the variable, so the meaning of these code samples is the same: "create a function and put it into the variable `sayHi`".
+
+In more advanced situations, that we'll come across later, a function may be created and immediately called or scheduled for a later execution, not stored anywhere, thus remaining anonymous.
+
+## Function is a value
+
+Let's reiterate: no matter how the function is created, a function is a value. Both examples above store a function in the `sayHi` variable.
+
+We can even print out that value using `alert`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function sayHi() {
@@ -32,6 +66,7 @@ function sayHi() {
}
*!*
+<<<<<<< HEAD
alert( sayHi ); // 関数のコードが表示されます
*/!*
```
@@ -79,6 +114,55 @@ let func = sayHi;
````smart header="なぜ末尾にセミコロンがあるのでしょう?"
疑問があるかもしれません。なぜ関数式は末尾にセミコロン `;` を持つのか、そして関数宣言にはそれがないのか:
+=======
+alert( sayHi ); // shows the function code
+*/!*
+```
+
+Please note that the last line does not run the function, because there are no parentheses after `sayHi`. There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that.
+
+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.
+
+Surely, a function is a special value, 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.
+
+We can copy a function to another variable:
+
+```js run no-beautify
+function sayHi() { // (1) create
+ alert( "Hello" );
+}
+
+let func = sayHi; // (2) copy
+
+func(); // Hello // (3) run the copy (it works)!
+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.
+3. Now the function can be called as both `sayHi()` and `func()`.
+
+We could also have used a Function Expression to declare `sayHi`, in the first line:
+
+```js
+let sayHi = function() { // (1) create
+ alert( "Hello" );
+};
+
+let func = sayHi; //(2)
+// ...
+```
+
+Everything would work the same.
+
+
+````smart header="Why is there a semicolon at the end?"
+You might wonder, why do Function Expressions have a semicolon `;` at the end, but Function Declarations do not:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function sayHi() {
@@ -90,6 +174,7 @@ let sayHi = function() {
}*!*;*/!*
```
+<<<<<<< HEAD
答えはシンプルです:
- コードブロックや `if { ... }`, `for { }`, `function f { }` などの構文構造の末尾には `;` が必要ありません。
- 関数式は文の内側で使われます: `let sayHi = ...;` の値として利用します。これはコードブロックではありません。セミコロン `;` はどんな値であれ文の最後に推奨されています。従って、ここのセミコロンは関数式自体と関係はなく、単に文の終わりです。
@@ -111,6 +196,29 @@ let sayHi = function() {
: 答えが "いいえ" の場合に実行する関数
関数は `question` を聞き、ユーザの回答に合わせて、`yes()` または `no()` を呼びます:
+=======
+The answer is simple: a Function Expression is created here as `function(…) {…}` inside the assignment statement: `let sayHi = …;`. The semicolon `;` is recommended at the end of the statement, it's not a part of the function syntax.
+
+The semicolon would be there for a simpler assignment, such as `let sayHi = 5;`, and it's also there for a function assignment.
+````
+
+## Callback functions
+
+Let's look at more examples of passing functions as values and using function expressions.
+
+We'll write a function `ask(question, yes, no)` with three parameters:
+
+`question`
+: Text of the question
+
+`yes`
+: Function to run if the answer is "Yes"
+
+`no`
+: Function to run if the answer is "No"
+
+The function should ask the `question` and, depending on the user's answer, call `yes()` or `no()`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
@@ -128,6 +236,7 @@ function showCancel() {
alert( "You canceled the execution." );
}
+<<<<<<< HEAD
// 使用法: 関数 showOk, showCancel は ask の引数として渡されます
ask("Do you agree?", showOk, showCancel);
```
@@ -139,6 +248,19 @@ ask("Do you agree?", showOk, showCancel);
このアイデアは、渡した関数が必要に応じて後から "コールバック" されることを期待するというものです。このケースでは、`showOK` は "はい" のためのコールバック関数になり、`showCancel` は "いいえ" の回答のためのコールバック関数です。
同じ関数をより短く書くために関数式を使うことができます:
+=======
+// usage: functions showOk, showCancel are passed as arguments to ask
+ask("Do you agree?", showOk, showCancel);
+```
+
+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 functions usually draw a nice-looking question window. But that's another story.
+
+**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 "yes" answer, and `showCancel` for "no" answer.
+
+We can use Function Expressions to write an equivalent, shorter function:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
function ask(question, yes, no) {
@@ -155,6 +277,7 @@ ask(
*/!*
```
+<<<<<<< HEAD
ここでは、関数は `ask(...)` 呼び出しの中で正しく宣言されています。これらは名前を持たないので *無名関数* と呼ばれます。このような関数は、変数に割り当てられていないため `ask` の外側からはアクセスできませんが、ここでは私たちにとってちょうどよいものとなっています。
このようなコードはスクリプトの中で自然に現れます。それは JavaScript の精神に基づいています。
@@ -178,19 +301,52 @@ ask(
```js
// 関数宣言
+=======
+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*.
+
+A function can be perceived as an *action*.
+
+We can pass it between variables and run when we want.
+```
+
+
+## Function Expression vs Function Declaration
+
+Let's formulate the key differences between Function Declarations and Expressions.
+
+First, the syntax: how to differentiate between them in the code.
+
+- *Function Declaration:* a function, declared as a separate statement, in the main code flow:
+
+ ```js
+ // Function Declaration
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
function sum(a, b) {
return a + b;
}
```
+<<<<<<< HEAD
- *関数式:* 式の内部、または別の構文構造の中で作れらた関数。ここでは、関数は "代入式" `=` の右側で作られます:
```js
// 関数式
+=======
+- *Function Expression:* a function, created inside an expression or inside another syntax construct. Here, the function is created on the right side of the "assignment expression" `=`:
+
+ ```js
+ // Function Expression
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let sum = function(a, b) {
return a + b;
};
```
+<<<<<<< HEAD
よりささいな違いは、関数がJavaScriptエンジンによって *作られたとき* です。
**関数式は、実行がそれに到達した時に作られ、それ以降で利用可能になります。**
@@ -208,6 +364,25 @@ ask(
結果的に、関数宣言として宣言された関数は、関数が定義されている場所よりも前で呼ぶことができます。
例えば、これは動作します:
+=======
+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 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 can be called earlier than it is defined.**
+
+For example, a global Function Declaration is visible in the whole script, no matter where it is.
+
+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".
+
+And after all Function Declarations are processed, the code is executed. So it has access to these functions.
+
+For example, this works:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run refresh untrusted
*!*
@@ -219,6 +394,7 @@ function sayHi(name) {
}
```
+<<<<<<< HEAD
関数宣言 `sayHi` は、JavaScriptがスクリプトの開始の準備をしているときに生成され、その中でどこからでも見えます。
...もしもそれが関数式だった場合、動作しないでしょう:
@@ -226,6 +402,15 @@ function sayHi(name) {
```js run refresh untrusted
*!*
sayHi("John"); // エラー!
+=======
+The Function Declaration `sayHi` is created when JavaScript is preparing to start the script and is visible everywhere in it.
+
+...If it were a Function Expression, then it wouldn't work:
+
+```js run refresh untrusted
+*!*
+sayHi("John"); // error!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
let sayHi = function(name) { // (*) no magic any more
@@ -233,6 +418,7 @@ let sayHi = function(name) { // (*) no magic any more
};
```
+<<<<<<< HEAD
関数式は、実行がそれに到達した時に作られます。それは行 `(*)` で起こります。遅すぎます。
**関数宣言がコードブロックの中で作られるとき、そのブロックの内側であればどこからでも見えます。しかし、その外側からは見えません。**
@@ -242,11 +428,26 @@ let sayHi = function(name) { // (*) no magic any more
例えば、ランタイムの中で得た `age` 変数に依存する関数 `welcome()` を宣言する必要があるとしましょう。そして、しばらくしてから使用する予定だとします。
下のコードはうまく動作しません:
+=======
+Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late.
+
+Another special feature of Function Declarations is their block scope.
+
+**In strict mode, when a Function Declaration is within a code block, it's visible everywhere inside that block. But not outside of it.**
+
+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.
+
+If we use Function Declaration, it won't work as intended:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt("What is your age?", 18);
+<<<<<<< HEAD
// 条件付きで関数を宣言する
+=======
+// conditionally declare a function
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
if (age < 18) {
function welcome() {
@@ -261,6 +462,7 @@ if (age < 18) {
}
+<<<<<<< HEAD
// ...後で使う
*!*
welcome(); // エラー: welcome は未定義です
@@ -285,15 +487,46 @@ if (age < 18) {
// |
*!*
welcome(); // / (実行)
+=======
+// ...use it later
+*!*
+welcome(); // Error: welcome is not defined
+*/!*
+```
+
+That's because a Function Declaration is only visible inside the code block in which it resides.
+
+Here's another example:
+
+```js run
+let age = 16; // take 16 as an example
+
+if (age < 18) {
+*!*
+ welcome(); // \ (runs)
+*/!*
+ // |
+ function welcome() { // |
+ alert("Hello!"); // | Function Declaration is available
+ } // | everywhere in the block where it's declared
+ // |
+*!*
+ welcome(); // / (runs)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
} else {
+<<<<<<< HEAD
function welcome() { // age = 16 の場合, この "welcome" は決して作られません
+=======
+ function welcome() {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert("Greetings!");
}
}
+<<<<<<< HEAD
// ここは、波括弧の外です
// なのでその中で作られた関数宣言は見ることができません
@@ -307,6 +540,21 @@ welcome(); // エラー: welcome は定義されていません
正しいアプローチは、関数式を使い、`welcome` を `if` の外で宣言し、適切なスコープをもつ変数に代入することです。
これは、意図したとおりに動作します:
+=======
+// Here we're out of curly braces,
+// so we can not see Function Declarations made inside of them.
+
+*!*
+welcome(); // Error: welcome is not defined
+*/!*
+```
+
+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.
+
+This code works as intended:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt("What is your age?", 18);
@@ -332,7 +580,11 @@ welcome(); // ok now
*/!*
```
+<<<<<<< HEAD
もしくは、疑問符演算子 `?` を使うことでさらにシンプルにできます:
+=======
+Or we could simplify it even further using a question mark operator `?`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt("What is your age?", 18);
@@ -347,6 +599,7 @@ welcome(); // ok now
```
+<<<<<<< HEAD
```smart header="関数宣言と関数式のどちらを選択するのか?"
経験則として、関数を宣言する必要があるとき、最初に考えるのは関数宣言構文です。関数が宣言される前に呼ぶことができるため、コードを体系化する自由度が増します。
@@ -366,3 +619,24 @@ welcome(); // ok now
たいていのケースでは、関数の宣言が必要な場合、関数宣言が望ましいです。なぜなら、それ自身の宣言の前でも利用することができるからです。これにより、コード構成の柔軟性が増し、通常は読みやすくなります。
従って、関数宣言がそのタスクに適さない場合にのみ関数式を使うべきです。この章ではそのような例をいくつか見てきましたが、今後もさらに多くの例を見ていくことになるでしょう。
+=======
+```smart header="When to choose Function Declaration versus Function Expression?"
+As a rule of thumb, when we need to declare a function, the first thing 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.
+
+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, or we need a conditional declaration (we've just seen an example), then Function Expression should be used.
+```
+
+## Summary
+
+- Functions are values. They can be assigned, copied or declared in any place of the code.
+- If the function is declared as a separate statement in the main code flow, that's called a "Function Declaration".
+- If the function is created as a part of an expression, it's called a "Function Expression".
+- 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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/solution.md b/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/solution.md
index 2557dda9f8..4a790d631c 100644
--- a/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/solution.md
+++ b/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/solution.md
@@ -1,7 +1,7 @@
```js run
function ask(question, yes, no) {
- if (confirm(question)) yes()
+ if (confirm(question)) yes();
else no();
}
diff --git a/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/task.md b/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/task.md
index 783419e867..9359c60d21 100644
--- a/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/task.md
+++ b/1-js/02-first-steps/17-arrow-functions-basics/1-rewrite-arrow/task.md
@@ -1,11 +1,15 @@
# アロー関数を使った書き換え
+<<<<<<< HEAD
次のコードで、関数式をアロー関数に置き換えてください。:
+=======
+Replace Function Expressions with arrow functions in the code below:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function ask(question, yes, no) {
- if (confirm(question)) yes()
+ if (confirm(question)) yes();
else no();
}
diff --git a/1-js/02-first-steps/17-arrow-functions-basics/article.md b/1-js/02-first-steps/17-arrow-functions-basics/article.md
index 9006138193..23bea12553 100644
--- a/1-js/02-first-steps/17-arrow-functions-basics/article.md
+++ b/1-js/02-first-steps/17-arrow-functions-basics/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# アロー関数の基本
関数を作成するための、よりシンプルで簡潔な構文がもう1つあります。それはしばしば関数式よりも優れています。
@@ -19,11 +20,38 @@ let func = function(arg1, arg2, ...argN) {
```
具体的な例を見てみましょう:
+=======
+# Arrow functions, the basics
+
+There's another very simple and concise syntax for creating functions, that's often better than Function Expressions.
+
+It's called "arrow functions", because it looks like this:
+
+```js
+let func = (arg1, arg2, ..., argN) => expression;
+```
+
+This creates a function `func` that accepts arguments `arg1..argN`, then evaluates the `expression` on the right side with their use and returns its result.
+
+In other words, it's the shorter version of:
+
+```js
+let func = function(arg1, arg2, ..., argN) {
+ return expression;
+};
+```
+
+Let's see a concrete example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let sum = (a, b) => a + b;
+<<<<<<< HEAD
/* アロー関数は次よりも短い形式です:
+=======
+/* This arrow function is a shorter form of:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let sum = function(a, b) {
return a + b;
@@ -33,22 +61,38 @@ let sum = function(a, b) {
alert( sum(1, 2) ); // 3
```
+<<<<<<< HEAD
ご覧の通り、`(a, b) => a + b` は `a` と `b` 、2つの引数を受け取る関数を意味します。実行時に、`a + b` を評価し、結果を返します。
- 引数が1つだけの場合、括弧は省略可能なので、さらに短くできます:
例:
+=======
+As you can see, `(a, b) => a + b` means a function that accepts two arguments named `a` and `b`. Upon the execution, it evaluates the expression `a + b` and returns the result.
+
+- If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
+
+ For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
let double = n => n * 2;
+<<<<<<< HEAD
// おおよそこちらと同じ: let double = function(n) { return n * 2 }
+=======
+ // roughly the same as: let double = function(n) { return n * 2 }
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert( double(3) ); // 6
```
+<<<<<<< HEAD
- 引数がない場合、空の括弧が必須です:
+=======
+- If there are no arguments, parentheses are empty, but they must be present:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let sayHi = () => alert("Hello!");
@@ -56,14 +100,21 @@ alert( sum(1, 2) ); // 3
sayHi();
```
+<<<<<<< HEAD
アロー関数は、関数式として同じ方法で使用できます。
例えば、ここでは `welcome()` の例を再び書きます:
+=======
+Arrow functions can be used in the same way as Function Expressions.
+
+For instance, to dynamically create a function:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
+<<<<<<< HEAD
() => alert('Hello') :
() => alert("Greetings!");
@@ -87,12 +138,38 @@ let sum = (a, b) => { // 波括弧を使って複数行の関数を書けます
let result = a + b;
*!*
return result; // 波括弧を使う場合、明示的な return が必要です
+=======
+ () => alert('Hello!') :
+ () => alert("Greetings!");
+
+welcome();
+```
+
+Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure.
+
+They are very convenient for simple one-line actions, when we're just too lazy to write many words.
+
+## Multiline arrow functions
+
+The arrow functions that we've seen so far were very simple. They took arguments from the left of `=>`, evaluated and returned the right-side expression with them.
+
+Sometimes we need a more complex function, with multiple expressions and statements. In that case, we can enclose them in curly braces. The major difference is that curly braces require a `return` within them to return a value (just like a regular function does).
+
+Like this:
+
+```js run
+let sum = (a, b) => { // the curly brace opens a multiline function
+ let result = a + b;
+*!*
+ return result; // if we use curly braces, then we need an explicit "return"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
};
alert( sum(1, 2) ); // 3
```
+<<<<<<< HEAD
```smart header="他にもあります"
ここでは、簡潔にするためにアロー関数を賞賛しました。しかし、それだけではありません!!
@@ -109,3 +186,21 @@ alert( sum(1, 2) ); // 3
1. 波括弧無し: `(...args) => expression` -- 右側は式です: 関数はそれを評価しその結果を返します。
2. 波括弧あり: `(...args) => { body }` -- 括弧があると、関数内で複数の文を書くことができます、しかし何かを返却する場合には、明示的な `return` が必要です。
+=======
+```smart header="More to come"
+Here we praised arrow functions for brevity. But that's not all!
+
+Arrow functions have other interesting features.
+
+To study them in-depth, we first need to get to know some other aspects of JavaScript, so we'll return to arrow functions later in the chapter .
+
+For now, we can already use arrow functions for one-line actions and callbacks.
+```
+
+## Summary
+
+Arrow functions are handy for simple actions, especially for one-liners. They come in two flavors:
+
+1. Without curly braces: `(...args) => expression` -- the right side is an expression: the function evaluates it and returns the result. Parentheses can be omitted, if there's only a single argument, e.g. `n => n*2`.
+2. With curly braces: `(...args) => { body }` -- brackets allow us to write multiple statements inside the function, but we need an explicit `return` to return something.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/02-first-steps/18-javascript-specials/article.md b/1-js/02-first-steps/18-javascript-specials/article.md
index 39131e0045..a5d084b81c 100644
--- a/1-js/02-first-steps/18-javascript-specials/article.md
+++ b/1-js/02-first-steps/18-javascript-specials/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# JavaScript スペシャル(これまでのおさらい)
このチャプターでは、微妙なケースに注意を払いながら、私たちが今まで学んだJavaScriptの機能を簡単に再確認します。
@@ -5,19 +6,36 @@
## コード構造
文はセミコロンで区切られます:
+=======
+# JavaScript specials
+
+This chapter briefly recaps the features of JavaScript that we've learned by now, paying special attention to subtle moments.
+
+## Code structure
+
+Statements are delimited with a semicolon:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
alert('Hello'); alert('World');
```
+<<<<<<< HEAD
通常、行の終わりは区切りとして扱われますので、これは動作します:
+=======
+Usually, a line-break is also treated as a delimiter, so that would also work:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run no-beautify
alert('Hello')
alert('World')
```
+<<<<<<< HEAD
これは "自動セミコロン挿入" と呼ばれます。ときどき、これは動作しません。例えば:
+=======
+That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert("There will be an error after this message")
@@ -25,6 +43,7 @@ alert("There will be an error after this message")
[1, 2].forEach(alert)
```
+<<<<<<< HEAD
ほとんどのコードスタイルのガイドは、各文の後にセミコロンを置くことに賛同しています。
セミコロンはコードブロック `{...}` や、ループのような構文構造の後では必要ありません:
@@ -46,6 +65,29 @@ for(;;) {
## Strict モード
現在のJavaScriptのすべての機能を完全に有効にするには、`"use strict"` でスクリプトを始める必要があります。
+=======
+Most codestyle guides agree that we should put a semicolon after each statement.
+
+Semicolons are not required after code blocks `{...}` and syntax constructs with them like loops:
+
+```js
+function f() {
+ // no semicolon needed after function declaration
+}
+
+for(;;) {
+ // no semicolon needed after the loop
+}
+```
+
+...But even if we can put an "extra" semicolon somewhere, that's not an error. It will be ignored.
+
+More in: .
+
+## Strict mode
+
+To fully enable all features of modern JavaScript, we should start scripts with `"use strict"`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
'use strict';
@@ -53,6 +95,7 @@ for(;;) {
...
```
+<<<<<<< HEAD
そのディレクティブはスクリプトの先頭、もしくは関数の最初である必要があります。
`"use strict"` がなくてもすべて動作しますが、幾つかの機能は "互換性のある" 旧来の振る舞いとなります。一般的に、現代的な動作が好まれるでしょう。
@@ -75,12 +118,37 @@ for(;;) {
- 非ラテンのアルファベットや象形文字も使えますが、一般的には使用されません。
変数は動的に型付けされます。 それらは任意の値を格納することができます:
+=======
+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-fashioned, "compatible" way. We'd generally prefer the modern behavior.
+
+Some modern features of the language (like classes that we'll study in the future) enable strict mode implicitly.
+
+More in: .
+
+## Variables
+
+Can be declared using:
+
+- `let`
+- `const` (constant, can't be changed)
+- `var` (old-style, will see later)
+
+A variable name can include:
+- Letters and digits, but the first character may not be a digit.
+- Characters `$` and `_` are normal, on par with letters.
+- Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used.
+
+Variables are dynamically typed. They can store any value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let x = 5;
x = "John";
```
+<<<<<<< HEAD
7つのデータ型があります:
- `number` 浮動少数点と整数値両方
@@ -115,6 +183,42 @@ typeof function(){} == "function" // 関数は特別に扱われます
それらの関数はすべて *モーダル* であり、コードの実行を止め、訪問者が回答するまでそのページとのやり取りを防ぎます。
例えば:
+=======
+There are 8 data types:
+
+- `number` for both floating-point and integer numbers,
+- `bigint` for integer numbers of arbitrary length,
+- `string` for strings,
+- `boolean` for logical values: `true/false`,
+- `null` -- a type with a single value `null`, meaning "empty" or "does not exist",
+- `undefined` -- a type with a single value `undefined`, meaning "not assigned",
+- `object` and `symbol` -- for complex data structures and unique identifiers, we haven't learnt them yet.
+
+The `typeof` operator returns the type for a value, with two exceptions:
+```js
+typeof null == "object" // error in the language
+typeof function(){} == "function" // functions are treated specially
+```
+
+More in: and .
+
+## Interaction
+
+We're using a browser as a working environment, so basic UI functions will be:
+
+[`prompt(question, [default])`](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)
+: Ask a `question`, and return either what the visitor entered or `null` if they clicked "cancel".
+
+[`confirm(question)`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
+: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`.
+
+[`alert(message)`](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
+: Output a `message`.
+
+All these functions are *modal*, they pause the code execution and prevent the visitor from interacting with the page until they answer.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let userName = prompt("Your name?", "Alice");
@@ -124,6 +228,7 @@ alert( "Visitor: " + userName ); // Alice
alert( "Tea wanted: " + isTeaWanted ); // true
```
+<<<<<<< HEAD
より詳細はこちらです: .
## 演算子
@@ -134,12 +239,25 @@ JavaScriptは次のような演算子をサポートします:
: 通常の四則演算の `* + - /`、また剰余として `%`、冪乗として `**`。
二項演算子プラス `+` は文字列を連結します。また、オペランドのいずれかが文字列であれば、もう一方も文字列に変換されます:
+=======
+More in: .
+
+## Operators
+
+JavaScript supports the following operators:
+
+Arithmetical
+: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number.
+
+ The binary plus `+` concatenates strings. And if any of the operands is a string, the other one is converted to string too:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( '1' + 2 ); // '12', string
alert( 1 + '2' ); // '12', string
```
+<<<<<<< HEAD
代入
: 単純な代入の `a = b` と `a *= 2` のような他の演算子と組み合わせたものがあります。
@@ -157,12 +275,32 @@ NULL合体演算子
比較
: 異なる型の値のための等価チェック `==` は、それらを数値に変換します(`null` と `undefined`を除きます。それらは、お互いに等しく、他とは等しくなりません)。従って以下は等価です。:
+=======
+Assignments
+: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
+
+Bitwise
+: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise_operators) when they are needed.
+
+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 (not necessary `true`/`false`). Logical NOT `!` converts the operand to boolean type and returns the inverse value.
+
+Nullish coalescing operator
+: The `??` operator provides a way to choose a defined value from a list of variables. The result of `a ?? b` is `a` unless it's `null/undefined`, then `b`.
+
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert( 0 == false ); // true
alert( 0 == '' ); // true
```
+<<<<<<< HEAD
他の比較も同様に数値に変換します。
厳密等価演算子 `===` は変換を行いません: 異なる型は常に異なる値を意味します。
@@ -179,6 +317,24 @@ NULL合体演算子
## ループ
- 私たちは3つのタイプのループを説明しました:
+=======
+ Other comparisons convert to a number as well.
+
+ The strict equality operator `===` doesn't do the conversion: different types always mean different values for it.
+
+ Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else.
+
+ Greater/less comparisons compare strings character-by-character, other types are converted to a number.
+
+Other operators
+: There are few others, like a comma operator.
+
+More in: , , , .
+
+## Loops
+
+- We covered 3 types of loops:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 1
@@ -197,6 +353,7 @@ NULL合体演算子
}
```
+<<<<<<< HEAD
- `for(let...)` ループの中で宣言された変数はループの内側でのみ見えます。しかし、`let` を省略することができ、既存の変数を再利用することも出来ます。
- ディレクティブ `break/continue` はループ全体/現在のイテレーションを終了させることができます。ネストされたループを停止する場合にはラベルを使ってください。
@@ -209,13 +366,32 @@ NULL合体演算子
"switch" 構造は複数の `if` チェックに置換できます。それは比較に `===` を使います。
例えば:
+=======
+- The variable declared in `for(let...)` loop is visible only inside the loop. But we can also omit `let` and reuse an existing variable.
+- Directives `break/continue` allow to exit the whole loop/current iteration. Use labels to break nested loops.
+
+Details in: .
+
+Later we'll study more types of loops to deal with objects.
+
+## The "switch" construct
+
+The "switch" construct can replace multiple `if` checks. It uses `===` (strict equality) for comparisons.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let age = prompt('Your age?', 18);
switch (age) {
case 18:
+<<<<<<< HEAD
alert("Won't work"); // プロンプトの結果は文字列であり、数値ではありません
+=======
+ alert("Won't work"); // the result of prompt is a string, not a number
+ break;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
case "18":
alert("This works!");
@@ -226,6 +402,7 @@ switch (age) {
}
```
+<<<<<<< HEAD
詳細はこちらです: .
## 関数
@@ -233,6 +410,15 @@ switch (age) {
私たちは、JavaScriptで関数を作る3つの方法をカバーしました。:
1. 関数宣言: メインコードフローの中の関数
+=======
+Details in: .
+
+## Functions
+
+We covered three ways to create a function in JavaScript:
+
+1. Function Declaration: the function in the main code flow
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function sum(a, b) {
@@ -242,13 +428,18 @@ switch (age) {
}
```
+<<<<<<< HEAD
2. 関数式: 式のコンテキストにある関数
+=======
+2. Function Expression: the function in the context of an expression
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let sum = function(a, b) {
let result = a + b;
return result;
+<<<<<<< HEAD
}
```
@@ -259,19 +450,39 @@ switch (age) {
let sum = (a, b) => a + b;
// もしくは { ... } を使った複数行の構文で、return が必要です:
+=======
+ };
+ ```
+
+3. Arrow functions:
+
+ ```js
+ // expression on the right side
+ let sum = (a, b) => a + b;
+
+ // or multi-line syntax with { ... }, need return here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let sum = (a, b) => {
// ...
return a + b;
}
+<<<<<<< HEAD
// 引数なし
let sayHi = () => alert("Hello");
// 1つの引数
+=======
+ // without arguments
+ let sayHi = () => alert("Hello");
+
+ // with a single argument
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let double = n => n * 2;
```
+<<<<<<< HEAD
- 関数はローカル変数を持ちます: それらはその関数本体の中で宣言されます。このような変数は関数の中でだけ見えます。
- パラメータはデフォルト値を持つことが出来ます。: `function sum(a = 1, b = 2) {...}`.
- 関数は常に何かを返します。もしも `return` 文がない場合は `undefined` を返します。
@@ -281,3 +492,14 @@ switch (age) {
## これからが本番です
ここまではJavaScriptの機能の簡単な一覧でした。今のところ、私たちは基本だけを学びました。このチュートリアルではさらに、JavaScriptのより特別で高度な機能について説明していきます。
+=======
+- Functions may have local variables: those declared inside its body or its parameter list. Such variables are only visible inside the function.
+- 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`.
+
+Details: see , .
+
+## More to come
+
+That was a brief list of JavaScript features. As of now we've studied only basics. Further in the tutorial you'll find more specials and advanced features of JavaScript.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 df0232f737..1a73d89a59 100644
--- a/1-js/03-code-quality/01-debugging-chrome/article.md
+++ b/1-js/03-code-quality/01-debugging-chrome/article.md
@@ -1,7 +1,12 @@
+<<<<<<< HEAD
# Chrome でのデバッグ
+=======
+# Debugging in the browser
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
より複雑なコードを書く前に、デバッグについて話しましょう。
+<<<<<<< HEAD
[デバッギング](https://en.wikipedia.org/wiki/Debugging)はスクリプト内のエラーを見つけ、修正するプロセスです。すべてのモダンブラウザと他の環境のほとんどはデバッギングツール(デバッグを簡単に行えるようにする開発者ツールのUI)をサポートしています。また、コードをステップ毎に追跡して正確に起きていることを確認することもできます。
ここでは、恐らくこの観点では最も機能が充実している Chrome を使います。
@@ -9,15 +14,29 @@
## "sources" パネル
Chromeのバージョンによっては少し違って見えるかもしれませんが、何があるかは明白でしょう。
+=======
+[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 has enough features, most other browsers have a similar process.
+
+## The "Sources" panel
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
- Chromeの [example page](debugging/index.html) を開きます。
- `key:F12` (Mac: `key:Cmd+Opt+I`) で開発者ツールをONにします。
- `source` パネルを選択します。
+<<<<<<< HEAD
この画面を見るのが初めてであれば、見ておくべきものがあります:
+=======
+- Open the [example page](debugging/index.html) in Chrome.
+- Turn on developer tools with `key:F12` (Mac: `key:Cmd+Opt+I`).
+- Select the `Sources` panel.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b

+<<<<<<< HEAD
トグルボタン はファイルを表示するタブを開きます。
それをクリックして、`index.html` 、次にツリービューの `hello.js` を選択しましょう。ここで表示される内容は次の通りです:
@@ -33,26 +52,61 @@ Chromeのバージョンによっては少し違って見えるかもしれま
同じトグル を再びクリックすること、リソースの一覧やコードを隠すことができます。
## コンソール
+=======
+
+
+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:
+
+
+
+The Sources panel has 3 parts:
+
+1. The **File Navigator** pane lists HTML, JavaScript, CSS and other files, including images that are attached to the page. Chrome extensions may appear here too.
+2. The **Code Editor** pane shows the source code.
+3. The **JavaScript Debugging** pane is for debugging, we'll explore it soon.
+
+Now you could click the same toggler again to hide the resources list and give the code some space.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
`Esc` を押すとコンソールが下に表示されます。そこでコマンドを入力し、`key:Enter` を押すとコマンドを実行することができます。
+<<<<<<< HEAD
実行結果は下に表示されます。
+=======
+If we press `key:Esc`, then a console opens below. We can type commands there and press `key:Enter` to execute.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例えば、ここでは `1+2 ` は `3` になり、`hello("debugger")` は何も返さないので、結果は `undefined` です:
+<<<<<<< HEAD

## ブレイクポイント
+=======
+For example, here `1+2` results in `3`, while the function call `hello("debugger")` returns nothing, so the result is `undefined`:
+
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
[example page](debugging/index.html) のコードの中で何が起こっているのか見てみましょう。`hello.js` で、行番号 `4` をクリックします。コードではなく、左側にある数字の `"4"` です。
+<<<<<<< HEAD
これでブレイクポイントがセットできました。行 `8` の数字もクリックしましょう。
+=======
+Let's examine what's going on within the code of the [example page](debugging/index.html). In `hello.js`, click at line number `4`. Yes, right on the `4` digit, not on the code.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
このようになるはずです(青はあなたがクリックした場所です):

+<<<<<<< HEAD
*ブレイクポイント* はデバッガが自動でJavaScriptの実行を停止するコードのポイントです。
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
コードが停止している間、現在の変数を検査したり、コンソールでコマンドを実行することができます。つまり、そこでデバッグができます。
@@ -62,6 +116,7 @@ Chromeのバージョンによっては少し違って見えるかもしれま
- 右クリックから削除を選択することで、ブレイクポイントを削除する
- ...など
+<<<<<<< HEAD
```smart header="条件付きのブレイクポイント"
行番号の *右クリック* で *条件付きの* ブレイクポイントを作ることができます。与えられた式が真の場合にのみトリガします。
@@ -71,6 +126,23 @@ Chromeのバージョンによっては少し違って見えるかもしれま
## デバッガコマンド
次のように、`debugger` コマンドを使うことでもコードを停止することができます:
+=======
+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.
+
+```smart header="Conditional breakpoints"
+*Right click* on the line number allows to create a *conditional* breakpoint. It only triggers when the given expression, that you should provide when you create it, is truthy.
+
+That's handy when we need to stop only for a certain variable value or for certain function parameters.
+```
+
+## The command "debugger"
+
+We can also pause the code by using the `debugger` command in it, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function hello(name) {
@@ -84,12 +156,20 @@ function hello(name) {
}
```
+<<<<<<< HEAD
これは、コードエディタで作業中、ブラウザに切り替えて開発者ツールを起動し、ブレイクポイントをセットするために開発者ツールでスクリプトを探すなどという手間をかけたくない場合にとても便利です。
+=======
+Such command works only when the development tools are open, otherwise the browser ignores it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## 一時停止して見回す
+<<<<<<< HEAD
今回の例では、`hello()` はページ読み込み中に呼び出されるので、デバッガを起動する最も簡単な方法はページを再読み込みすることです。なので、 `key:F5` (Windows, Linux)または `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).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
ブレイクポイントがセットされているので、実行は4行目で一時停止します。:
@@ -99,14 +179,23 @@ function hello(name) {
1. **`Watch` -- 任意の式の現在の値を表示します。**
+<<<<<<< HEAD
`+` をクリックし、式を入力することができます。デバッガは、常にその値を表示し、実行中に自動的に再計算を行います。
+=======
+ You can click the plus `+` and input an expression. The debugger will show its value, automatically recalculating it in the process of execution.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
2. **`Call Stack` -- ネストされた呼び出しのチェーンを表示します。**
現時点では、デバッガは `hello()` 呼び出しの内側におり、`index.html` のスクリプト(そこに関数はないので、 "anonymous" と呼ばれます)によって呼び出されました。
+<<<<<<< HEAD
スタックの項目をクリックすると、デバッガは該当のコードにジャンプし、すべての変数も同様に調べられます。
3. **`Scope` -- 現在の変数。**
+=======
+ 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.**
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
`Local` はローカル関数の変数を表示します。また、ソース上でもハイライト表示されたそれらの値を見ることができます。
@@ -118,15 +207,23 @@ function hello(name) {
スクリプトを *追跡* してみましょう。
+<<<<<<< HEAD
右ペインの上部にそのボタンがあります。
-- "再開": 実行の継続, ホットキー `key:F8`.
: 実行を再開します。もしも他にブレイクポイントがなければ、そのまま実行が継続され、デバッガの制御から外れます。
次の図は、それを行った後に見える画面です:
+=======
+There are buttons for it at the top of the right panel. Let's engage them.
+
+ -- "Resume": 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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b

+<<<<<<< HEAD
実行は再開され、`say()` の中の別のブレイクポイントに到達し、そこで一時停止します。右の "Call stack" を見てください。もう一度呼び出すことで増えています。私たちは、今 `say()` の中にいます。
-- "ステップ": 次のコマンドを実行します, ホットキー `key:F9`.
@@ -156,32 +253,78 @@ function hello(name) {
-- エラー発生時の自動一時停止の有効/無効
: 有効にして開発者ツールを開いている場合、スクリプトエラーが起きると実行が自動で一時停止します。そして、何が間違っていたかを知るために変数を分析することができます。なので、スクリプトがエラーで死んだ場合は、どこで死んでその時どんなコンテキストであるかを確認するため、デバッガを起動しこのオプションを有効にしてページを再読込しましょう。
+=======
+ 
+
+ 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.
+
+ -- "Step": run the next command, hotkey `key:F9`.
+: Run the next statement. If we click it now, `alert` will be shown.
+
+ Clicking this again and again will step through all script statements one by one.
+
+ -- "Step over": run the next command, but *don't go into a function*, hotkey `key:F10`.
+: Similar to the previous "Step" command, but behaves differently if the next statement is a function call (not a built-in, like `alert`, but a function of our own).
+
+ If we compare them, the "Step" command goes into a nested function call and pauses the execution at its first line, while "Step over" executes the nested function call invisibly to us, skipping the function internals.
+
+ The execution is then paused immediately after that function call.
+
+ That's good if we're not interested to see what happens inside the function call.
+
+ -- "Step into", hotkey `key:F11`.
+: That's similar to "Step", but behaves differently in case of asynchronous function calls. If you're only starting to learn JavaScript, then you can ignore the difference, as we don't have asynchronous calls yet.
+
+ For the future, just note that "Step" command ignores async actions, such as `setTimeout` (scheduled function call), that execute later. The "Step into" goes into their code, waiting for them if necessary. See [DevTools manual](https://developers.google.com/web/updates/2018/01/devtools#async) for more details.
+
+ -- "Step out": continue the execution till the end of the current function, hotkey `key:Shift+F11`.
+: Continue the execution and stop it at the very last line of the current function. That's handy when we accidentally entered a nested call using , but it does not interest us, and we want to continue to its end as soon as possible.
+
+ -- enable/disable all breakpoints.
+: That button does not move the execution. Just a mass on/off for breakpoints.
+
+ -- enable/disable automatic pause in case of an error.
+: When enabled, if the developer tools is open, an error during the script execution automatically pauses it. Then we can analyze variables in the debugger to see what went wrong. So if our script dies with an error, we can open debugger, enable this option and reload the page to see where it dies and what's the context at that moment.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```smart header="Continue to here"
コードの行で右クリックすると、"Continue to here" と呼ばれる素晴らしい選択肢を持つコンテキストメニューが開きます。
+<<<<<<< HEAD
これは複数のステップを進めたいが、ブレイクポイントをセットするのが面倒なときに便利です。
+=======
+That's handy when we want to move multiple steps forward to the line, but we're too lazy to set a breakpoint.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
## ロギング
+<<<<<<< HEAD
コンソールに何かを出力するために `console.log` 関数があります。
+=======
+To output something to console from our code, there's `console.log` function.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
例えば、これはコンソールに `0` から `4` までの値を出力します:
```js run
// 見るにはコンソールを開いてください
for (let i = 0; i < 5; i++) {
- console.log("value", i);
+ console.log("value,", i);
}
```
+<<<<<<< HEAD
コンソールの中なので、通常のユーザはその出力を見ることはありません。見るためには、開発者ツールのコンソールタブを開くか、開発者ツールの別のタブで `key:Esc` を押します。 :下にコンソールが表示されます。
+=======
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
コードに十分なログを仕込んでいれば、デバッガなしで何が行われているか知ることができます。
## サマリ
+<<<<<<< HEAD
これまで見てきた通り、スクリプトを一時停止するには主に3つの方法があります。
1. ブレイクポイント
2. `debugger` 文
@@ -190,7 +333,21 @@ for (let i = 0; i < 5; i++) {
これらにより変数を検査し実行が間違っている場所を確認することができます。
ここで説明した以上に、開発者ツールには多くのオプションがあります。完全なマニュアルは です。
+=======
+As we can see, there are three main ways to pause a script:
+1. A breakpoint.
+2. The `debugger` statements.
+3. An error (if dev tools are open and the button is "on").
+
+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 .
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
このチャプターの情報はデバッグを始めるには十分ですが、今後、特にブラウザの作業が多い場合は、上記のサイトを見て開発者ツールのより高度な機能を調べてください。
+<<<<<<< HEAD
また、開発者ツールの色んな場所をクリックすることで何が表示されるかを見ることが出来ます。恐らくそれは開発者ツールを学ぶのに最も近道です。同様に右クリックも忘れないように!
+=======
+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!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index a3c7db6ec4..a647276e8f 100644
--- 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
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index 6e7b60f854..d7aaabf02e 100644
--- 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
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index d5d2a0b934..36e7a2be6d 100644
--- 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
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index 83468fddb1..3720509e70 100644
--- 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
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index 23937e0d68..757a2578b6 100644
--- 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
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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
index 41a3d8784b..f0e9afd019 100644
--- a/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg
+++ b/1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md
index 60a22707d1..0b0fd240d3 100644
--- a/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md
+++ b/1-js/03-code-quality/02-coding-style/1-style-errors/solution.md
@@ -2,6 +2,7 @@
あなたは次のような事に気づけます:
```js no-beautify
+<<<<<<< HEAD
function pow(x,n) // <- 引数の間にスペースがない
{ // <- 別の行に波括弧がある
let result=1; // <- = の両側にスペースがない
@@ -15,11 +16,30 @@ let x=prompt("x?",''), n=prompt("n?",'') // <-- 技術的には可能ですが,
if (n<0) // <- (n < 0) の中にスペースがありません。また、その上に余分な行があるべきです。
{ // <- 波括弧が別の行に分かれています
// 下は -- 1行が長いです。2行に分けたほうがよいです
+=======
+function pow(x,n) // <- no space between arguments
+{ // <- figure bracket on a separate line
+ let result=1; // <- no spaces before or after =
+ for(let i=0;i>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(`Power ${n} is not supported, please enter an integer number greater than zero`);
}
else // <- "} else {" のように1行で書いたほうがいいです。
{
+<<<<<<< HEAD
alert(pow(x,n)) // spaces と ; がありません。
+=======
+ alert(pow(x,n)) // no spaces and missing ;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
```
@@ -39,7 +59,7 @@ function pow(x, n) {
let x = prompt("x?", "");
let n = prompt("n?", "");
-if (n < 0) {
+if (n <= 0) {
alert(`Power ${n} is not supported,
please enter an integer number greater than zero`);
} else {
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 60e3fd1480..157be1d5e6 100644
--- a/1-js/03-code-quality/02-coding-style/article.md
+++ b/1-js/03-code-quality/02-coding-style/article.md
@@ -1,13 +1,26 @@
+<<<<<<< HEAD
# コーディングスタイル
+=======
+# Coding Style
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
コードはできるだけ綺麗で読みやすいものでなければなりません。
+<<<<<<< HEAD
複雑なタスクを正しくかつ読みやすい形でコード化する、それはまさにプログラミングの極意です。優れたコーディングスタイルは、そのための大きな助けとなるのです。
## 構文
下記は、いくつかの推奨ルールを示したチートシートです(詳細は後述):
+=======
+That is actually the art of programming -- to take a complex task and code it in a way that is both correct and human-readable. A good code style greatly assists in that.
+
+## Syntax
+
+Here is a cheat sheet with some suggested rules (see below for more details):
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b

@@ -45,4 +46,7 @@
-
\ No newline at end of file
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/02-function-prototype/1-changing-prototype/solution.md b/1-js/08-prototypes/02-function-prototype/1-changing-prototype/solution.md
index 519f90650b..e5b68bed22 100644
--- a/1-js/08-prototypes/02-function-prototype/1-changing-prototype/solution.md
+++ b/1-js/08-prototypes/02-function-prototype/1-changing-prototype/solution.md
@@ -3,6 +3,7 @@ Answers:
1. `true`.
+<<<<<<< HEAD
`Rabbit.prototype` への代入は、新しいオブジェクトに対して `[[Prototype]]` を設定しますが、既存のものへの影響はありません。
2. `false`.
@@ -18,3 +19,20 @@ Answers:
4. `undefined`.
プロトタイプから `eats` プロパティが削除されたので、もう存在していません。
+=======
+ The assignment to `Rabbit.prototype` sets up `[[Prototype]]` for new objects, but it does not affect the existing ones.
+
+2. `false`.
+
+ Objects are assigned by reference. The object from `Rabbit.prototype` is not duplicated, it's still a single object referenced both by `Rabbit.prototype` and by the `[[Prototype]]` of `rabbit`.
+
+ So when we change its content through one reference, it is visible through the other one.
+
+3. `true`.
+
+ All `delete` operations are applied directly to the object. Here `delete rabbit.eats` tries to remove `eats` property from `rabbit`, but it doesn't have it. So the operation won't have any effect.
+
+4. `undefined`.
+
+ The property `eats` is deleted from the prototype, it doesn't exist any more.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md b/1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md
index aa7ee9e6f0..806f265a1a 100644
--- a/1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md
+++ b/1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md
@@ -20,7 +20,11 @@ alert( rabbit.eats ); // true
```
+<<<<<<< HEAD
1. 1つ文字列を追加しました(強調部分)。今 `alert` は何が表示されるでしょう?
+=======
+1. We added one more string (emphasized). What will `alert` show now?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function Rabbit() {}
@@ -54,7 +58,11 @@ alert( rabbit.eats ); // true
alert( rabbit.eats ); // ?
```
+<<<<<<< HEAD
3. この場合は (1行置き換えました)?
+=======
+3. And like this (replaced one line)?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function Rabbit() {}
diff --git a/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/solution.md b/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/solution.md
index ca49c2ade7..5cf0dc7884 100644
--- a/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/solution.md
+++ b/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/solution.md
@@ -1,6 +1,12 @@
+<<<<<<< HEAD
もし `"constructor"` プロパティが正しい値を持っていることが確かであるなら、私たちはこのようなアプローチを使うことができます。
例えば、デフォルトの `"prototype"` を触らないのであれば、このコードは確実に動作します:
+=======
+We can use such approach if we are sure that `"constructor"` property has the correct value.
+
+For instance, if we don't touch the default `"prototype"`, then this code works for sure:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function User(name) {
@@ -13,11 +19,19 @@ let user2 = new user.constructor('Pete');
alert( user2.name ); // Pete (worked!)
```
+<<<<<<< HEAD
`User.prototype.constructor == User` であるため、これは動作します。
..しかし、いわば誰かが `User.prototype` を上書きし、`"constructor"` を再作成するのを忘れている場合、それは失敗するでしょう。
例:
+=======
+It worked, because `User.prototype.constructor == User`.
+
+..But if someone, so to speak, overwrites `User.prototype` and forgets to recreate `constructor` to reference `User`, then it would fail.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function User(name) {
@@ -33,6 +47,7 @@ let user2 = new user.constructor('Pete');
alert( user2.name ); // undefined
```
+<<<<<<< HEAD
なぜ `user2.name` が `undefined` なのでしょう?
ここで、`new user.constructor('Pete')` は次のように動作します:
@@ -42,3 +57,19 @@ alert( user2.name ); // undefined
3. `User.prototype` の値は普通のオブジェクト `{}` であり、そのプロトタイプは `Object.prototype` です。そして、`Object.prototype.constructor == Object` があります。なので、これが使われます。
最終的に、`let user2 = new Object('Pete')` となります。組み込みの `Object` コンストラクタは引数を無視し、常に空のオブジェクトを生成します -- これは、結局私たちが `user2` で持っているものです。
+=======
+Why `user2.name` is `undefined`?
+
+Here's how `new user.constructor('Pete')` works:
+
+1. First, it looks for `constructor` in `user`. Nothing.
+2. Then it follows the prototype chain. The prototype of `user` is `User.prototype`, and it also has no `constructor` (because we "forgot" to set it right!).
+3. Going further up the chain, `User.prototype` is a plain object, its prototype is the built-in `Object.prototype`.
+4. Finally, for the built-in `Object.prototype`, there's a built-in `Object.prototype.constructor == Object`. So it is used.
+
+Finally, at the end, we have `let user2 = new Object('Pete')`.
+
+Probably, that's not what we want. We'd like to create `new User`, not `new Object`. That's the outcome of the missing `constructor`.
+
+(Just in case you're curious, the `new Object(...)` call converts its argument to an object. That's a theoretical thing, in practice no one calls `new Object` with a value, and generally we don't use `new Object` to make objects at all).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md b/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
index b8b14f2312..2093310365 100644
--- a/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
+++ b/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
@@ -2,14 +2,26 @@ importance: 5
---
+<<<<<<< HEAD
# 同じコンストラクタでオブジェクトを作成する
想像してください、コンストラクタ関数によって作成された任意のオブジェクト `obj` があります -- 今、それを使って新しいオブジェクトを作りたいです。
私たちは、このようにすることができるでしょうか?
+=======
+# Create an object with the same constructor
+
+Imagine, we have an arbitrary object `obj`, created by a constructor function -- we don't know which one, but we'd like to create a new object using it.
+
+Can we do it like that?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let obj2 = new obj.constructor();
```
+<<<<<<< HEAD
このコードを正しく動作させる `obj` のコンストラクタ関数の例を提示してください。そして、間違って動作する例も提示してください。
+=======
+Give an example of a constructor function for `obj` which lets such code work right. And an example that makes it work wrong.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/02-function-prototype/article.md b/1-js/08-prototypes/02-function-prototype/article.md
index f4593cda9d..bbd914d687 100644
--- a/1-js/08-prototypes/02-function-prototype/article.md
+++ b/1-js/08-prototypes/02-function-prototype/article.md
@@ -1,5 +1,6 @@
# F.prototype
+<<<<<<< HEAD
思い出してください、新しいオブジェクトは `new F()` のように、コンストラクタ関数で生成できます。
`F.prototype` がオブジェクトの場合、`new` 演算子は新しいオブジェクトで `[[Prototype]]` をセットするためにそれを使用します。
@@ -13,6 +14,21 @@ JavaScriptは最初からプロトタイプの継承を持っています。 そ
ここで `F.prototype` は `F` 上の `"prototype"` と名付けられた通常のプロパティを意味していることに注意してください。用語 "プロトタイプ" と似ていますが、ここでは本当にその名前をもつ通常のプロパティを意味しています。
ここではその例です:
+=======
+Remember, new objects can be created with a constructor function, like `new F()`.
+
+If `F.prototype` is an object, then the `new` operator uses it to set `[[Prototype]]` for the new object.
+
+```smart
+JavaScript had prototypal inheritance from the beginning. It was one of the core features of the language.
+
+But in the old times, there was no direct access to it. The only thing that worked reliably was a `"prototype"` property of the constructor function, described in this chapter. So there are many scripts that still use it.
+```
+
+Please note that `F.prototype` here means a regular property named `"prototype"` on `F`. It sounds something similar to the term "prototype", but here we really mean a regular property with this name.
+
+Here's the example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
@@ -32,6 +48,7 @@ let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal
alert( rabbit.eats ); // true
```
+<<<<<<< HEAD
`Rabbit.prototype = animal` の設定は、文字通り次のことを述べています。: "`new Rabbit` が生成される時、その `[[Prototype]]` へ `animal` を割り当てます。"
これが結果のイメージです:
@@ -53,27 +70,63 @@ alert( rabbit.eats ); // true
デフォルトの `"prototype"` は `constructor` というプロパティだけを持つオブジェクトで、それは関数自体を指します。
こんな感じです:
+=======
+Setting `Rabbit.prototype = animal` literally states the following: "When a `new Rabbit` is created, assign its `[[Prototype]]` to `animal`".
+
+That's the resulting picture:
+
+
+
+On the picture, `"prototype"` is a horizontal arrow, meaning a regular property, and `[[Prototype]]` is vertical, meaning the inheritance of `rabbit` from `animal`.
+
+```smart header="`F.prototype` only used at `new F` time"
+`F.prototype` property is only used when `new F` is called, it assigns `[[Prototype]]` of the new object.
+
+If, after the creation, `F.prototype` property changes (`F.prototype = `), then new objects created by `new F` will have another object as `[[Prototype]]`, but already existing objects keep the old one.
+```
+
+## Default F.prototype, constructor property
+
+Every function has the `"prototype"` property even if we don't supply it.
+
+The default `"prototype"` is an object with the only property `constructor` that points back to the function itself.
+
+Like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function Rabbit() {}
+<<<<<<< HEAD
/* デフォルト prototype
+=======
+/* default prototype
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
Rabbit.prototype = { constructor: Rabbit };
*/
```

+<<<<<<< HEAD
コードでそれを確認できます:
```js run
function Rabbit() {}
// デフォルトでは:
+=======
+We can check it:
+
+```js run
+function Rabbit() {}
+// by default:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// Rabbit.prototype = { constructor: Rabbit }
alert( Rabbit.prototype.constructor == Rabbit ); // true
```
+<<<<<<< HEAD
当然、何もしない場合、 `constructor` プロパティは `[[Prototype]]` を通じてすべての rabbit が利用できます。:
```js run
@@ -84,13 +137,31 @@ function Rabbit() {}
let rabbit = new Rabbit(); // {constructor: Rabbit} の継承
alert(rabbit.constructor == Rabbit); // true (prototype から)
+=======
+Naturally, if we do nothing, the `constructor` property is available to all rabbits through `[[Prototype]]`:
+
+```js run
+function Rabbit() {}
+// by default:
+// Rabbit.prototype = { constructor: Rabbit }
+
+let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}
+
+alert(rabbit.constructor == Rabbit); // true (from prototype)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```

+<<<<<<< HEAD
`constructor` プロパティを使って既存のものと同じコンストラクタを使って新しいオブジェクトを作成することができます。
このように:
+=======
+We can use `constructor` property to create a new object using the same constructor as the existing one.
+
+Like here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function Rabbit(name) {
@@ -105,6 +176,7 @@ let rabbit2 = new rabbit.constructor("Black Rabbit");
*/!*
```
+<<<<<<< HEAD
これは、オブジェクトを持っているが、どのコンストラクタが使われたか分からない場合(例えばサードパーティーのライブラリが使われているなど)で、同じ種類のものを使って別のオブジェクトを作る必要がある場合に便利です。
しかし、おそらく `"constructor"` に関する最も重要なことは...
@@ -116,6 +188,19 @@ let rabbit2 = new rabbit.constructor("Black Rabbit");
特に、もしデフォルトプロトタイプ全体を置き換えると、その中に `"constructor"` はなくなります。
例:
+=======
+That's handy when we have an object, don't know which constructor was used for it (e.g. it comes from a 3rd party library), and we need to create another one of the same kind.
+
+But probably the most important thing about `"constructor"` is that...
+
+**...JavaScript itself does not ensure the right `"constructor"` value.**
+
+Yes, it exists in the default `"prototype"` for functions, but that's all. What happens with it later -- is totally on us.
+
+In particular, if we replace the default prototype as a whole, then there will be no `"constructor"` in it.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function Rabbit() {}
@@ -129,11 +214,16 @@ alert(rabbit.constructor === Rabbit); // false
*/!*
```
+<<<<<<< HEAD
したがって、正しい `"constructor"` を維持するためには、全体を上書きする代わりに、デフォルト `"prototype"` に対して追加/削除を行います。:
+=======
+So, to keep the right `"constructor"` we can choose to add/remove properties to the default `"prototype"` instead of overwriting it as a whole:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function Rabbit() {}
+<<<<<<< HEAD
// 完全に Rabbit.prototype を上書きはしません
// 単に追加するだけです
Rabbit.prototype.jumps = true
@@ -141,6 +231,15 @@ Rabbit.prototype.jumps = true
```
もしくは、代替として手動で `constructor` プロパティを再び作ります。:
+=======
+// Not overwrite Rabbit.prototype totally
+// just add to it
+Rabbit.prototype.jumps = true
+// the default Rabbit.prototype.constructor is preserved
+```
+
+Or, alternatively, recreate the `constructor` property manually:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
Rabbit.prototype = {
@@ -150,6 +249,7 @@ Rabbit.prototype = {
*/!*
};
+<<<<<<< HEAD
// 追加したので、これで constructor も正しいです
```
@@ -165,6 +265,23 @@ Rabbit.prototype = {
- `"prototype"` プロパティはコンストラクタ関数に設定され、`new` で呼び出されたときにのみ、特別な効果があります。
通常のオブジェクトでは、`prototype` は特別なものではありません。:
+=======
+// now constructor is also correct, because we added it
+```
+
+
+## Summary
+
+In this chapter we briefly described the way of setting a `[[Prototype]]` for objects created via a constructor function. Later we'll see more advanced programming patterns that rely on it.
+
+Everything is quite simple, just a few notes to make things clear:
+
+- The `F.prototype` property (don't mistake it for `[[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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let user = {
name: "John",
@@ -172,4 +289,8 @@ let user = {
};
```
+<<<<<<< HEAD
デフォルトでは、すべての関数は `F.prototype = { constructor: F }` を持っているので、その `"constructor"` プロパティへアクセスすることで、オブジェクトの constructor を取得することができます。
+=======
+By default all functions have `F.prototype = { constructor: F }`, so we can get the constructor of an object by accessing its `"constructor"` property.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md b/1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md
index b913fe9007..8b92e15297 100644
--- a/1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md
+++ b/1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md
@@ -2,16 +2,28 @@ importance: 5
---
+<<<<<<< HEAD
# 関数にメソッド "f.defer(ms)" を追加する
すべての関数プロトタイプにメソッド `defer(ms)` を追加してください。それは `ms` ミリ秒後に関数を実行します。
その後、このようなコードが動くはずです。:
+=======
+# Add method "f.defer(ms)" to functions
+
+Add to the prototype of all functions the method `defer(ms)`, that runs the function after `ms` milliseconds.
+
+After you do it, such code should work:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function f() {
alert("Hello!");
}
+<<<<<<< HEAD
f.defer(1000); // 1秒後に "Hello!" が表示される
+=======
+f.defer(1000); // shows "Hello!" after 1 second
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
diff --git a/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md b/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md
index e3651683fa..2af84e8f67 100644
--- a/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md
+++ b/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md
@@ -15,3 +15,30 @@ function f(a, b) {
f.defer(1000)(1, 2); // shows 3 after 1 sec
```
+<<<<<<< HEAD
+=======
+
+Please note: we use `this` in `f.apply` to make our decoration work for object methods.
+
+So if the wrapper function is called as an object method, then `this` is passed to the original method `f`.
+
+```js run
+Function.prototype.defer = function(ms) {
+ let f = this;
+ return function(...args) {
+ setTimeout(() => f.apply(this, args), ms);
+ }
+};
+
+let user = {
+ name: "John",
+ sayHi() {
+ alert(this.name);
+ }
+}
+
+user.sayHi = user.sayHi.defer(1000);
+
+user.sayHi();
+```
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md b/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md
index 81341420a2..02f348bb7f 100644
--- a/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md
+++ b/1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md
@@ -2,18 +2,33 @@ importance: 4
---
+<<<<<<< HEAD
# デコレートする "defer()" を関数に追加する
すべての関数のプロトタイプにメソッド `defer(ms)` を追加してください。それはラッパーを返し、`ms` ミリ秒呼び出しを遅延します。
これは、どのように動作すべきか、の例です:
+=======
+# Add the decorating "defer()" to functions
+
+Add to the prototype of all functions the method `defer(ms)`, that returns a wrapper, delaying the call by `ms` milliseconds.
+
+Here's an example of how it should work:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function f(a, b) {
alert( a + b );
}
+<<<<<<< HEAD
f.defer(1000)(1, 2); // 1秒後に 3 が表示される
```
引数をオリジナルの関数に渡す必要があることに注意してください。
+=======
+f.defer(1000)(1, 2); // shows 3 after 1 second
+```
+
+Please note that the arguments should be passed to the original function.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/03-native-prototypes/article.md b/1-js/08-prototypes/03-native-prototypes/article.md
index d9b3167af7..1256319f6c 100644
--- a/1-js/08-prototypes/03-native-prototypes/article.md
+++ b/1-js/08-prototypes/03-native-prototypes/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# ネイティブのプロトタイプ
`"prototype"` プロパティはJavaScript自身のコア部分で広く使われています。すべての組み込みのコンストラクタ関数はこれを使用しています。
@@ -7,12 +8,24 @@
## Object.prototype
空のオブジェクトを出力してみましょう。:
+=======
+# Native prototypes
+
+The `"prototype"` property is widely used by the core of JavaScript itself. All built-in constructor functions use it.
+
+First we'll look at the details, and then how to use it for adding new capabilities to built-in objects.
+
+## Object.prototype
+
+Let's say we output an empty object:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let obj = {};
alert( obj ); // "[object Object]" ?
```
+<<<<<<< HEAD
文字列 `"[object Object]"` を生成するコードはどこにあるのでしょう? それは組み込みの `toString` メソッドですが、どこにあるのでしょう? `obj` は空です!
...しかし、短い記法 `obj = {}` は `obj = new Object()` と同じで、その `Object` は組み込みのオブジェクトコンストラクタ関数です。その関数は `toString` や他の関数を持つ巨大なオブジェクトを参照する `Object.prototype` を持っています。
@@ -28,6 +41,23 @@ alert( obj ); // "[object Object]" ?
その後、`obj.toString()` が呼ばれると、`Object.prototype` からメソッドが取り出されます。
このようにして確認できます:
+=======
+Where's the code that generates the string `"[object Object]"`? That's a built-in `toString` method, but where is it? The `obj` is empty!
+
+...But the short notation `obj = {}` is the same as `obj = new Object()`, where `Object` is a built-in object constructor function, with its own `prototype` referencing a huge object with `toString` and other methods.
+
+Here's what's going on:
+
+
+
+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:
+
+
+
+So then when `obj.toString()` is called the method is taken from `Object.prototype`.
+
+We can check it like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let obj = {};
@@ -38,12 +68,17 @@ alert(obj.toString === obj.__proto__.toString); //true
alert(obj.toString === Object.prototype.toString); //true
```
+<<<<<<< HEAD
上の `Object.prototype` のチェーンで、追加の `[[Prototype]]` がないことに注意してください。:
+=======
+Please note that there is no more `[[Prototype]]` in the chain above `Object.prototype`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
alert(Object.prototype.__proto__); // null
```
+<<<<<<< HEAD
## 他の組み込みのプロトタイプ
`Array`, `Date`, `Function` のような、他の組み込みのオブジェクトもまたプロトタイプにメソッドを保持しています。
@@ -57,10 +92,26 @@ alert(Object.prototype.__proto__); // null

プロトタイプを手動でチェックしてみましょう。:
+=======
+## Other built-in prototypes
+
+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 `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. That's why some people say that "everything inherits from objects".
+
+Here's the overall picture (for 3 built-ins to fit):
+
+
+
+Let's check the prototypes manually:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let arr = [1, 2, 3];
+<<<<<<< HEAD
// Array.prototype から継承している?
alert( arr.__proto__ === Array.prototype ); // true
@@ -79,21 +130,50 @@ alert(arr); // 1,2,3 <-- Array.prototype.toString の結果
```
以前見たように、`Object.prototype` も同様に `toString` を持っていますが、`Array.prototype` はチェーンでより近い位置にあるので、配列がもつものが使用されます。
+=======
+// it inherits from Array.prototype?
+alert( arr.__proto__ === Array.prototype ); // true
+
+// then from Object.prototype?
+alert( arr.__proto__.__proto__ === Object.prototype ); // true
+
+// and null on the top.
+alert( arr.__proto__.__proto__.__proto__ ); // null
+```
+
+Some methods in prototypes may overlap, for instance, `Array.prototype` has its own `toString` that lists comma-delimited elements:
+
+```js run
+let arr = [1, 2, 3]
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b

+<<<<<<< HEAD
Chrome developer console のようなブラウザ内のツールでも継承を表示できます(組み込みオブジェクトのために `console.dir` を使う必要があるかもしれません)。

他の組み込みオブジェクトも同じように動作します。関数でさえも、それらは組み込みの `Function` コンストラクタのオブジェクトであり、メソッドです: `call/apply` など、`Function.prototype` から取り出されたものです。関数には独自の `toString`もあります。
+=======
+In-browser tools like Chrome developer console also show inheritance (`console.dir` may need to be used for built-in objects):
+
+
+
+Other built-in objects also work the same way. Even functions -- they are objects of a built-in `Function` constructor, and their methods (`call`/`apply` and others) are taken from `Function.prototype`. Functions have their own `toString` too.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function f() {}
alert(f.__proto__ == Function.prototype); // true
+<<<<<<< HEAD
alert(f.__proto__.__proto__ == Object.prototype); // true, object からの継承
```
@@ -112,6 +192,26 @@ alert(f.__proto__.__proto__ == Object.prototype); // true, object からの継
## ネイティブプロトタイプの変更
ネイティブプロトタイプは変更することができます。例えば、もしあるメソッドを `String.prototype` に追加した場合、それはすべての文字列で利用可能になります。:
+=======
+alert(f.__proto__.__proto__ == Object.prototype); // true, inherit from objects
+```
+
+## Primitives
+
+The most intricate thing happens with strings, numbers and booleans.
+
+As we remember, they are not objects. But if we try to access their properties, temporary wrapper objects are created using built-in constructors `String`, `Number` and `Boolean`. They provide the methods and disappear.
+
+These objects are created invisibly to us and most engines optimize them out, but the specification describes it exactly this way. Methods of these objects also reside in prototypes, available as `String.prototype`, `Number.prototype` and `Boolean.prototype`.
+
+```warn header="Values `null` and `undefined` have no object wrappers"
+Special values `null` and `undefined` stand apart. They have no object wrappers, so methods and properties are not available for them. And there are no corresponding prototypes either.
+```
+
+## Changing native prototypes [#native-prototype-change]
+
+Native prototypes can be modified. For instance, if we add a method to `String.prototype`, it becomes available to all strings:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
String.prototype.show = function() {
@@ -121,6 +221,7 @@ String.prototype.show = function() {
"BOOM!".show(); // BOOM!
```
+<<<<<<< HEAD
開発の過程で、新しい組み込みメソッドを追加したいと考えてるかもしれません。そして、それをネイティブプロトタイプに加えたいという、若干の誘惑があるかもしれません。ですが、それは一般的には悪い考えです。
```
@@ -147,6 +248,34 @@ if (!String.prototype.repeat) { // もしこのようなメソッドがない場
// 実際、このコードはこれより複雑になります
// "n" の負の値に対するエラーのスロー
// 完全なアルゴリズムは仕様にあります
+=======
+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 method of the other.
+
+So, generally, modifying a native prototype is considered a bad idea.
+```
+
+**In modern programming, there is only one case where modifying native prototypes is approved. That's polyfilling.**
+
+Polyfilling is a term for making a substitute for a method that exists in the JavaScript specification, but is not yet supported by a particular JavaScript engine.
+
+We may then implement it manually and populate the built-in prototype with it.
+
+For instance:
+
+```js run
+if (!String.prototype.repeat) { // if there's no such method
+ // add it to the prototype
+
+ String.prototype.repeat = function(n) {
+ // repeat the string n times
+
+ // 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
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return new Array(n + 1).join(this);
};
}
@@ -155,6 +284,7 @@ alert( "La".repeat(3) ); // LaLaLa
```
+<<<<<<< HEAD
## プロトタイプからの借用
チャプター で私たちはメソッドの借用について話しました。:
@@ -166,6 +296,19 @@ alert( "La".repeat(3) ); // LaLaLa
例えば、配列ライクなオブジェクトを作成している場合、そこにいくつかの `Array` メソッドをそこにコピーしたい場合があります。
例
+=======
+## Borrowing from prototypes
+
+In the chapter we talked about method borrowing.
+
+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.
+
+E.g.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let obj = {
@@ -181,6 +324,7 @@ obj.join = Array.prototype.join;
alert( obj.join(',') ); // Hello,world!
```
+<<<<<<< HEAD
組み込みの `join` メソッドの内部アルゴリズムは、正しいインデックスと `length` プロパティのみを考慮するため、これは機能します。オブジェクトがたしかに配列かどうかはチェックしません。多くの組み込みメソッドはこのようになっています。
別の可能性は、`obj.__proto__` を `Array.prototype` に設定することで継承することで、これによりすべての `Array` メソッドは自動的に `obj` で利用可能になります。
@@ -196,3 +340,20 @@ alert( obj.join(',') ); // Hello,world!
- オブジェクト自身はデータのみを保持します(配列アイテム、オブジェクトプロパティ、日付)。
- プリミティブもまたラッパーオブジェクトのプロトタイプにメソッドを保持します。: `Number.prototype`, `String.prototype`, `Boolean.prototype` 。`undefined` と `null` にだけはラッパーオブジェクトはありません。
- 組み込みのプロトタイプを変更したり、新しいメソッドを実装することができます。 しかし、それを変更することはお勧めしません。 おそらく唯一許可されるケースは、新しい標準が追加されたものの、まだエンジンのJavaScriptメソッドではサポートされていないときだけです。
+=======
+It works because the internal algorithm of the built-in `join` method only cares about the correct indexes and the `length` property. It doesn't check if the object is indeed an array. Many built-in methods are like that.
+
+Another possibility is to inherit by setting `obj.__proto__` to `Array.prototype`, so all `Array` methods are automatically available in `obj`.
+
+But that's impossible if `obj` already inherits from another object. Remember, we only can inherit from one object at a time.
+
+Borrowing methods is flexible, it allows to mix functionalities from different objects if needed.
+
+## Summary
+
+- All built-in objects follow the same pattern:
+ - The methods are stored in the prototype (`Array.prototype`, `Object.prototype`, `Date.prototype`, etc.)
+ - The object itself stores only the data (array items, object properties, the date)
+- Primitives also store methods in prototypes of wrapper objects: `Number.prototype`, `String.prototype` and `Boolean.prototype`. Only `undefined` and `null` do not have wrapper objects
+- Built-in prototypes can be modified or populated with new methods. But it's not recommended to change them. The only allowable case is probably when we add-in a new standard, but it's not yet supported by the JavaScript engine
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/solution.md b/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/solution.md
index d0c04e5e5d..97fa1f3c6c 100644
--- a/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/solution.md
+++ b/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/solution.md
@@ -1,13 +1,24 @@
+<<<<<<< HEAD
このメソッドは `Object.keys` を使ってすべての列挙可能なキーを取り、そのリストを出力します。
`toString` を非列挙型にするために、プロパティディスクリプタを使って定義しましょう。`Object.create` の構文は、2番目の引数としてプロパティディスクリプタのオブジェクトを指定することができます。
+=======
+The method can take all enumerable keys using `Object.keys` and output their list.
+
+To make `toString` non-enumerable, let's define it using a property descriptor. The syntax of `Object.create` allows us to provide an object with property descriptors as the second argument.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
let dictionary = Object.create(null, {
+<<<<<<< HEAD
toString: { // toString プロパティの定義
value() { // 値は関数です
+=======
+ toString: { // define toString property
+ value() { // the value is a function
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return Object.keys(this).join();
}
}
@@ -17,13 +28,27 @@ let dictionary = Object.create(null, {
dictionary.apple = "Apple";
dictionary.__proto__ = "test";
+<<<<<<< HEAD
// ループでは apple と __proto__ だけです
+=======
+// apple and __proto__ is in the loop
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for(let key in dictionary) {
alert(key); // "apple", then "__proto__"
}
+<<<<<<< HEAD
// toString によるカンマ区切りのプロパティのリスト
alert(dictionary); // "apple,__proto__"
```
ディスクリプタを使ってプロパティを作成するとき、そのフラグはデフォルトでは `false` です。なので、上のコードで。`dictionary.toString` は非列挙型です。
+=======
+// comma-separated list of properties by toString
+alert(dictionary); // "apple,__proto__"
+```
+
+When we create a property using a descriptor, its flags are `false` by default. So in the code above, `dictionary.toString` is non-enumerable.
+
+See the chapter [](info:property-descriptors) for review.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/task.md b/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/task.md
index 1abda4180f..fb6be6ccea 100644
--- a/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/task.md
+++ b/1-js/08-prototypes/04-prototype-methods/2-dictionary-tostring/task.md
@@ -2,6 +2,7 @@ importance: 5
---
+<<<<<<< HEAD
# 辞書に toString を追加する
任意の `key/value` ペアを格納するために `Object.create(null)` として生成されたオブジェクト `dictonary` があります。
@@ -9,11 +10,21 @@ importance: 5
その中にメソッド `dictionary.toString()` を追加してください。それはカンマ区切りのキーのリストを返します。あなたの `toString` はオブジェクト上の `for..in` で現れるべきではありません。
次のように動作します:
+=======
+# Add toString to the dictionary
+
+There's an object `dictionary`, created as `Object.create(null)`, to store any `key/value` pairs.
+
+Add method `dictionary.toString()` into it, that should return a comma-delimited list of keys. Your `toString` should not show up in `for..in` over the object.
+
+Here's how it should work:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let dictionary = Object.create(null);
*!*
+<<<<<<< HEAD
// dictionary.toString メソッドを追加するあなたのコード
*/!*
@@ -22,10 +33,24 @@ dictionary.apple = "Apple";
dictionary.__proto__ = "test"; // __proto__ はここでは通常のプロパティキー
// ループでは apple と __proto__ だけです
+=======
+// your code to add dictionary.toString method
+*/!*
+
+// add some data
+dictionary.apple = "Apple";
+dictionary.__proto__ = "test"; // __proto__ is a regular property key here
+
+// only apple and __proto__ are in the loop
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for(let key in dictionary) {
alert(key); // "apple", then "__proto__"
}
+<<<<<<< HEAD
// 実行時のあなたの toString です
+=======
+// your toString in action
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(dictionary); // "apple,__proto__"
```
diff --git a/1-js/08-prototypes/04-prototype-methods/3-compare-calls/task.md b/1-js/08-prototypes/04-prototype-methods/3-compare-calls/task.md
index 9839aeb326..87f4b28c85 100644
--- a/1-js/08-prototypes/04-prototype-methods/3-compare-calls/task.md
+++ b/1-js/08-prototypes/04-prototype-methods/3-compare-calls/task.md
@@ -2,7 +2,11 @@ importance: 5
---
+<<<<<<< HEAD
# 呼び出し感の差異
+=======
+# The difference between calls
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
新しい `rabbit` オブジェクトを作りましょう:
diff --git a/1-js/08-prototypes/04-prototype-methods/article.md b/1-js/08-prototypes/04-prototype-methods/article.md
index 651f70f0fa..8da45ea2ee 100644
--- a/1-js/08-prototypes/04-prototype-methods/article.md
+++ b/1-js/08-prototypes/04-prototype-methods/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# __proto__ なしでの プロトタイプ メソッド, オブジェクト
このセクションの最初の最初の章では、プロトタイプ をセットアップする現代のメソッドを説明します。
@@ -14,20 +15,47 @@
これらは `__proto__` の代わりに使用します。
例:
+=======
+# Prototype methods, objects without __proto__
+
+In the first chapter of this section, we mentioned that there are modern methods to setup a prototype.
+
+Setting or reading the prototype with `obj.__proto__` is considered outdated and somewhat deprecated (moved to the so-called "Annex B" of the JavaScript standard, meant for browsers only).
+
+The modern methods to get/set a prototype are:
+
+- [Object.getPrototypeOf(obj)](mdn:js/Object/getPrototypeOf) -- returns the `[[Prototype]]` of `obj`.
+- [Object.setPrototypeOf(obj, proto)](mdn:js/Object/setPrototypeOf) -- sets the `[[Prototype]]` of `obj` to `proto`.
+
+The only usage of `__proto__`, that's not frowned upon, is as a property when creating a new object: `{ __proto__: ... }`.
+
+Although, there's a special method for this too:
+
+- [Object.create(proto[, descriptors])](mdn:js/Object/create) -- creates an empty object with given `proto` as `[[Prototype]]` and optional property descriptors.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
eats: true
};
+<<<<<<< HEAD
// animal をプロトタイプとして新しいオブジェクトを作成する
*!*
let rabbit = Object.create(animal);
+=======
+// create a new object with animal as a prototype
+*!*
+let rabbit = Object.create(animal); // same as {__proto__: animal}
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(rabbit.eats); // true
*!*
+<<<<<<< HEAD
alert(Object.getPrototypeOf(rabbit) === animal); // rabbit のプロトタイプを取得
*/!*
@@ -37,6 +65,19 @@ Object.setPrototypeOf(rabbit, {}); // rabbit のプロトタイプを {} に変
```
`Object.create` は任意で2つ目の引数を持ち、これはプロパティディスクリプタです。次のように、新しいオブジェクトに追加のプロパティが指定できます :
+=======
+alert(Object.getPrototypeOf(rabbit) === animal); // true
+*/!*
+
+*!*
+Object.setPrototypeOf(rabbit, {}); // change the prototype of rabbit to {}
+*/!*
+```
+
+The `Object.create` method is a bit more powerful, as it has an optional second argument: property descriptors.
+
+We can provide additional properties to the new object there, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
@@ -52,6 +93,7 @@ let rabbit = Object.create(animal, {
alert(rabbit.jumps); // true
```
+<<<<<<< HEAD
ディスクリプタはチャプター で説明したのと同じフォーマットです。
`for..in` でプロパティをコピーするよりも、より強力にオブジェクトをクローンするのに `Object.create` が使用できます。:
@@ -91,6 +133,55 @@ let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescr
...しかし、もしその中で *ユーザから提供された* キーを格納しようとした場合(例えばユーザが入力した辞書)、興味深い問題が起こります。: すべてのキーは `"__proto__"` を除いてうまく動作します。
例を確認してみましょう:
+=======
+The descriptors are in the same format as described in the chapter .
+
+We can use `Object.create` to perform an object cloning more powerful than copying properties in `for..in`:
+
+```js
+let clone = Object.create(
+ Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)
+);
+```
+
+This call makes a truly exact copy of `obj`, including all properties: enumerable and non-enumerable, data properties and setters/getters -- everything, and with the right `[[Prototype]]`.
+
+
+## Brief history
+
+There're so many ways to manage `[[Prototype]]`. How did that happen? Why?
+
+That's for historical reasons.
+
+The prototypal inheritance was in the language since its dawn, but the ways to manage it evolved over time.
+
+- The `prototype` property of a constructor function has worked since very ancient times. It's the oldest way to create objects with a given prototype.
+- Later, in the year 2012, `Object.create` appeared in the standard. It gave the ability to create objects with a given prototype, but did not provide the ability to get/set it. Some browsers implemented the non-standard `__proto__` accessor that allowed the user to get/set a prototype at any time, to give more flexibility to developers.
+- Later, in the year 2015, `Object.setPrototypeOf` and `Object.getPrototypeOf` were added to the standard, to perform the same functionality as `__proto__`. As `__proto__` was de-facto implemented everywhere, it was kind-of deprecated and made its way to the Annex B of the standard, that is: optional for non-browser environments.
+- Later, in the year 2022, it was officially allowed to use `__proto__` in object literals `{...}` (moved out of Annex B), but not as a getter/setter `obj.__proto__` (still in Annex B).
+
+Why was `__proto__` replaced by the functions `getPrototypeOf/setPrototypeOf`?
+
+Why was `__proto__` partially rehabilitated and its usage allowed in `{...}`, but not as a getter/setter?
+
+That's an interesting question, requiring us to understand why `__proto__` is bad.
+
+And soon we'll get the answer.
+
+```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 don't modify it anymore: `rabbit` inherits from `animal`, and that is not going to change.
+
+And JavaScript engines are highly optimized for this. Changing a prototype "on-the-fly" with `Object.setPrototypeOf` or `obj.__proto__=` is a very slow operation as it breaks internal optimizations for object property access operations. So avoid it unless you know what you're doing, or JavaScript speed totally doesn't matter for you.
+```
+
+## "Very plain" objects [#very-plain]
+
+As we know, objects can be used as associative arrays to store key/value pairs.
+
+...But if we try to store *user-provided* keys in it (for instance, a user-entered dictionary), we can see an interesting glitch: all keys work fine except `"__proto__"`.
+
+Check out the example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let obj = {};
@@ -98,6 +189,7 @@ let obj = {};
let key = prompt("What's the key?", "__proto__");
obj[key] = "some value";
+<<<<<<< HEAD
alert(obj[key]); // [object Object], "some value" ではありません!
```
@@ -128,10 +220,57 @@ alert(obj[key]); // [object Object], "some value" ではありません!
最初に言ったとおり、`__proto__` は `[[Prototype]]` にアクセスする方法であり、`[[Prototype]]` 自身ではありません。
今、連想配列としてオブジェクトを使いたい場合、リテラルのトリックを使ってそれを行う事ができます。:
+=======
+alert(obj[key]); // [object Object], not "some value"!
+```
+
+Here, if the user types in `__proto__`, the assignment in line 4 is ignored!
+
+That could surely be surprising for a non-developer, but pretty understandable for us. The `__proto__` property is special: it must be either an object or `null`. A string can not become a prototype. That's why assigning a string to `__proto__` is ignored.
+
+But we didn't *intend* to implement such behavior, right? We want to store key/value pairs, and the key named `"__proto__"` was not properly saved. So that's a bug!
+
+Here the consequences are not terrible. But in other cases we may be storing objects instead of strings in `obj`, and then the prototype will indeed be changed. As a result, the execution will go wrong in totally unexpected ways.
+
+What's worse -- 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 assigning to `obj.toString`, as it's a built-in object method.
+
+How can we avoid this problem?
+
+First, we can just switch to using `Map` for storage instead of plain objects, then everything's fine:
+
+```js run
+let map = new Map();
+
+let key = prompt("What's the key?", "__proto__");
+map.set(key, "some value");
+
+alert(map.get(key)); // "some value" (as intended)
+```
+
+...But `Object` syntax is often more appealing, as it's more concise.
+
+Fortunately, we *can* use objects, because language creators gave thought to that problem long ago.
+
+As we know, `__proto__` is not a property of an object, but an accessor property of `Object.prototype`:
+
+
+
+So, if `obj.__proto__` is read or set, the corresponding getter/setter is called from its prototype, and it gets/sets `[[Prototype]]`.
+
+As it was said in the beginning of this tutorial section: `__proto__` is a way to access `[[Prototype]]`, it is not `[[Prototype]]` itself.
+
+Now, if we intend to use an object as an associative array and be free of such problems, we can do it with a little trick:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
let obj = Object.create(null);
+<<<<<<< HEAD
+=======
+// or: obj = { __proto__: null }
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
let key = prompt("What's the key?", "__proto__");
@@ -140,6 +279,7 @@ obj[key] = "some value";
alert(obj[key]); // "some value"
```
+<<<<<<< HEAD
`Object.create(null)` はプロトタイプなし(`[[Prototype]]` が `null`)の空オブジェクトを作ります。:

@@ -149,6 +289,17 @@ alert(obj[key]); // "some value"
このようなオブジェクトを "非常にシンプルな" または "純粋な辞書オブジェクト" と呼びます。なぜなら、それらは通常のオブジェクト `{...}` よりもシンプルなためです。
欠点は、そのようなオブジェクトには組み込みのオブジェクトメソッドがないことです。 `toString` など:
+=======
+`Object.create(null)` creates an empty object without a prototype (`[[Prototype]]` is `null`):
+
+
+
+So, there is no inherited getter/setter for `__proto__`. Now it is processed as a regular data property, so the example above works right.
+
+We can call such objects "very plain" or "pure dictionary" objects, because they are even simpler than the regular plain object `{...}`.
+
+A downside is that such objects lack any built-in object methods, e.g. `toString`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
@@ -158,19 +309,31 @@ let obj = Object.create(null);
alert(obj); // Error (no toString)
```
+<<<<<<< HEAD
...しかし、連想配列ではそれは通常問題ありません。
ほとんどのオブジェクトに関連したメソッドは `Object.keys(obj)` のように `Object.something(...)` であることに注目してください。それらはプロトタイプにはないので、このようなオブジェクトで機能し続けます。:
+=======
+...But that's usually fine for associative arrays.
+
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let chineseDictionary = Object.create(null);
+<<<<<<< HEAD
chineseDictionary.hello = "ni hao";
chineseDictionary.bye = "zai jian";
+=======
+chineseDictionary.hello = "你好";
+chineseDictionary.bye = "再见";
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(Object.keys(chineseDictionary)); // hello,bye
```
+<<<<<<< HEAD
## サマリ
プロトタイプをセットアップしたり直接アクセスするための現代のメソッドは次の通りです:
@@ -202,3 +365,30 @@ let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescr
- [obj.hasOwnProperty(key)](mdn:js/Object/hasOwnProperty): それは `obj` 自身が `key` という名前のプロパティをもつ(継承でない) 場合に `true` を返します。
オブジェクトプロパティ(`Object.keys` など)を返すすべてのメソッドは "自身の" プロパティを返します。もし継承されたものが欲しい場合は、`for..in` を使います。
+=======
+## Summary
+
+- To create an object with the given prototype, use:
+
+ - literal syntax: `{ __proto__: ... }`, allows to specify multiple properties
+ - or [Object.create(proto[, descriptors])](mdn:js/Object/create), allows to specify property descriptors.
+
+ The `Object.create` provides an easy way to shallow-copy an object with all descriptors:
+
+ ```js
+ let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
+ ```
+
+- Modern methods to get/set 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).
+
+- Getting/setting the prototype using the built-in `__proto__` getter/setter isn't recommended, it's now in the Annex B of the specification.
+
+- We also covered prototype-less objects, created with `Object.create(null)` or `{__proto__: null}`.
+
+ These objects are used as dictionaries, to store any (possibly user-generated) keys.
+
+ Normally, objects inherit built-in methods and `__proto__` getter/setter from `Object.prototype`, making corresponding keys "occupied" and potentially causing side effects. With `null` prototype, objects are truly empty.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/08-prototypes/index.md b/1-js/08-prototypes/index.md
index 3943c1af9f..e4b51b1ae7 100644
--- a/1-js/08-prototypes/index.md
+++ b/1-js/08-prototypes/index.md
@@ -1 +1,5 @@
+<<<<<<< HEAD
# プロトタイプ, 継承
+=======
+# Prototypes, inheritance
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/solution.js b/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/solution.js
new file mode 100644
index 0000000000..0b31cf334e
--- /dev/null
+++ b/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/solution.js
@@ -0,0 +1,38 @@
+class Clock {
+ constructor({ template }) {
+ this.template = template;
+ }
+
+ render() {
+ let date = new Date();
+
+ let hours = date.getHours();
+ if (hours < 10) hours = '0' + hours;
+
+ let mins = date.getMinutes();
+ if (mins < 10) mins = '0' + mins;
+
+ let secs = date.getSeconds();
+ if (secs < 10) secs = '0' + secs;
+
+ let output = this.template
+ .replace('h', hours)
+ .replace('m', mins)
+ .replace('s', secs);
+
+ console.log(output);
+ }
+
+ stop() {
+ clearInterval(this.timer);
+ }
+
+ start() {
+ this.render();
+ this.timer = setInterval(() => this.render(), 1000);
+ }
+}
+
+
+let clock = new Clock({template: 'h:m:s'});
+clock.start();
diff --git a/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/source.js b/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/source.js
new file mode 100644
index 0000000000..f1749c8ba5
--- /dev/null
+++ b/1-js/09-classes/01-class/1-rewrite-to-class/_js.view/source.js
@@ -0,0 +1,37 @@
+function Clock({ template }) {
+
+ let timer;
+
+ function render() {
+ let date = new Date();
+
+ let hours = date.getHours();
+ if (hours < 10) hours = '0' + hours;
+
+ let mins = date.getMinutes();
+ if (mins < 10) mins = '0' + mins;
+
+ let secs = date.getSeconds();
+ if (secs < 10) secs = '0' + secs;
+
+ let output = template
+ .replace('h', hours)
+ .replace('m', mins)
+ .replace('s', secs);
+
+ console.log(output);
+ }
+
+ this.stop = function() {
+ clearInterval(timer);
+ };
+
+ this.start = function() {
+ render();
+ timer = setInterval(render, 1000);
+ };
+
+}
+
+let clock = new Clock({template: 'h:m:s'});
+clock.start();
diff --git a/1-js/09-classes/01-class/1-rewrite-to-class/solution.view/clock.js b/1-js/09-classes/01-class/1-rewrite-to-class/solution.view/clock.js
index c710b9da9b..d701c0caeb 100644
--- a/1-js/09-classes/01-class/1-rewrite-to-class/solution.view/clock.js
+++ b/1-js/09-classes/01-class/1-rewrite-to-class/solution.view/clock.js
@@ -1,21 +1,21 @@
class Clock {
constructor({ template }) {
- this._template = template;
+ this.template = template;
}
- _render() {
+ render() {
let date = new Date();
let hours = date.getHours();
if (hours < 10) hours = '0' + hours;
let mins = date.getMinutes();
- if (mins < 10) min = '0' + mins;
+ if (mins < 10) mins = '0' + mins;
let secs = date.getSeconds();
if (secs < 10) secs = '0' + secs;
- let output = this._template
+ let output = this.template
.replace('h', hours)
.replace('m', mins)
.replace('s', secs);
@@ -24,11 +24,11 @@ class Clock {
}
stop() {
- clearInterval(this._timer);
+ clearInterval(this.timer);
}
start() {
- this._render();
- this._timer = setInterval(() => this._render(), 1000);
+ this.render();
+ this.timer = setInterval(() => this.render(), 1000);
}
}
diff --git a/1-js/09-classes/01-class/1-rewrite-to-class/task.md b/1-js/09-classes/01-class/1-rewrite-to-class/task.md
index 7713cc62eb..0d4f24a562 100644
--- a/1-js/09-classes/01-class/1-rewrite-to-class/task.md
+++ b/1-js/09-classes/01-class/1-rewrite-to-class/task.md
@@ -2,8 +2,16 @@ importance: 5
---
+<<<<<<< HEAD
# クラスで書き直す
プロトタイプでの `Clock` クラスを、現代の "class" 構文で書き直してください。
P.S. 時計はコンソールで動きます、開いて見てください。
+=======
+# Rewrite to class
+
+The `Clock` class (see the sandbox) is written in functional style. Rewrite it in the "class" syntax.
+
+P.S. The clock ticks in the console, open it to see.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/01-class/article.md b/1-js/09-classes/01-class/article.md
index 4980210b93..b57786b385 100644
--- a/1-js/09-classes/01-class/article.md
+++ b/1-js/09-classes/01-class/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# クラス(Class) 基本構文
```quote author="Wikipedia"
@@ -17,6 +18,26 @@
```js
class MyClass {
// クラスメソッド
+=======
+# Class basic syntax
+
+```quote author="Wikipedia"
+In object-oriented programming, a *class* is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).
+```
+
+In practice, we often need to create many objects of the same kind, like users, or goods or whatever.
+
+As we already know from the chapter , `new function` can help with that.
+
+But in the modern JavaScript, there's a more advanced "class" construct, that introduces great new features which are useful for object-oriented programming.
+
+## The "class" syntax
+
+The basic syntax is:
+```js
+class MyClass {
+ // class methods
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
constructor() { ... }
method1() { ... }
method2() { ... }
@@ -25,11 +46,19 @@ class MyClass {
}
```
+<<<<<<< HEAD
その後、`new MyClass()` で、リストされたすべてのメソッドをもつ新しいオブジェクトを作成します。
`constructor()` メソッドは `new` により自動で呼び出され、そこでオブジェクトを初期化できます。
例
+=======
+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.
+
+For example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -44,11 +73,16 @@ class User {
}
+<<<<<<< HEAD
// 使い方:
+=======
+// Usage:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let user = new User("John");
user.sayHi();
```
+<<<<<<< HEAD
`new User("John")` が呼び出されると:
1. 新しいオブジェクトが作られます。
2. 指定された引数で `constructor` が実行され、`this.name` へ代入します。
@@ -71,6 +105,30 @@ user.sayHi();
JavaScript ではクラスは関数の一種です。
これを見てください:
+=======
+When `new User("John")` is called:
+1. A new object is created.
+2. The `constructor` runs with the given argument and assigns it to `this.name`.
+
+...Then we can call object methods, such as `user.sayHi()`.
+
+
+```warn header="No comma between class methods"
+A common pitfall for novice developers is to put a comma between class methods, which would result in a syntax error.
+
+The notation here is not to be confused with object literals. Within the class, no commas are required.
+```
+
+## What is a class?
+
+So, what exactly is a `class`? That's not an entirely new language-level entity, as one might think.
+
+Let's unveil any magic and see what a class really is. That'll help in understanding many complex aspects.
+
+In JavaScript, a class is a kind of function.
+
+Here, take a look:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -78,12 +136,17 @@ class User {
sayHi() { alert(this.name); }
}
+<<<<<<< HEAD
// 証拠: User は function です
+=======
+// proof: User is a function
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
alert(typeof User); // function
*/!*
```
+<<<<<<< HEAD
`class User {...}` 構造は実際に行っていることは以下です:
1. クラス宣言の結果となる `User` と言う名前の関数を作成します。関数コードは `constructor` メソッドです(メソッドがない場合は空と想定します)。
@@ -96,6 +159,20 @@ 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).
+2. Stores class methods, such as `sayHi`, in `User.prototype`.
+
+After `new User` object is created, when we call its 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:
+
+
+
+Here's the code to introspect it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -103,6 +180,7 @@ class User {
sayHi() { alert(this.name); }
}
+<<<<<<< HEAD
// class は function
alert(typeof User); // function
@@ -131,15 +209,50 @@ function User(name) {
// なので、作成は不要です
// 2. prototype へメソッドを追加
+=======
+// class is a function
+alert(typeof User); // function
+
+// ...or, more precisely, the constructor method
+alert(User === User.prototype.constructor); // true
+
+// The methods are in User.prototype, e.g:
+alert(User.prototype.sayHi); // the code of the sayHi method
+
+// there are exactly two methods in the prototype
+alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi
+```
+
+## Not just a syntactic sugar
+
+Sometimes people say that `class` is a "syntactic sugar" (syntax that is designed to make things easier to read, but doesn't introduce anything new), because we could actually declare the same thing without using the `class` keyword at all:
+
+```js run
+// rewriting class User in pure functions
+
+// 1. Create constructor function
+function User(name) {
+ this.name = name;
+}
+// a function prototype has "constructor" property by default,
+// so we don't need to create it
+
+// 2. Add the method to prototype
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
User.prototype.sayHi = function() {
alert(this.name);
};
+<<<<<<< HEAD
// 使い方:
+=======
+// Usage:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let user = new User("John");
user.sayHi();
```
+<<<<<<< HEAD
この定義の結果はほぼ同じです。なので、コンストラクタとそのプロトタイプメソッドを一緒に定義するための、`class` のシンタックスシュガーとみなされる理由はたしかにあります。
ですが、重要な違いがあります。
@@ -148,16 +261,33 @@ user.sayHi();
言語は様々な箇所でそのプロパティをチェックします。例えば通常の関数とは異なり、`new` で呼び出す必要があります:
+=======
+The result of this definition is about the same. So, there are indeed reasons why `class` can be considered a syntactic sugar to define a constructor together with its prototype methods.
+
+Still, there are important differences.
+
+1. First, a function created by `class` is labelled by a special internal property `[[IsClassConstructor]]: true`. So it's not entirely the same as creating it manually.
+
+ The language checks for that property in a variety of places. For example, unlike a regular function, it must be called with `new`:
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
constructor() {}
}
alert(typeof User); // function
+<<<<<<< HEAD
User(); // Error: クラスのコンストラクタ User は `new` なしで呼び出せません
```
また、ほとんどの JavaScript エンジンではクラスのコンストラクタの文字列表現は、"class..." で始まります
+=======
+ User(); // Error: Class constructor User cannot be invoked without 'new'
+ ```
+
+ Also, a string representation of a class constructor in most JavaScript engines starts with the "class..."
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -166,6 +296,7 @@ user.sayHi();
alert(User); // class User { ... }
```
+<<<<<<< HEAD
他の違いもあります。この後見ていきます。
2. クラス メソッドは列挙不可です
@@ -185,6 +316,25 @@ user.sayHi();
関数と同じように、クラスも別の式の中で定義し、渡したり、返却したり代入することができます。
これはクラス式の例です。:
+=======
+ There are other differences, we'll see them soon.
+
+2. Class methods are non-enumerable.
+ A class definition sets `enumerable` flag to `false` for all methods in the `"prototype"`.
+
+ That's good, because if we `for..in` over an object, we usually don't want its class methods.
+
+3. Classes always `use strict`.
+ All code inside the class construct is automatically in strict mode.
+
+Besides, `class` syntax brings many other features that we'll explore later.
+
+## Class Expression
+
+Just like functions, classes can be defined inside another expression, passed around, returned, assigned, etc.
+
+Here's an example of a class expression:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let User = class {
@@ -194,6 +344,7 @@ let User = class {
};
```
+<<<<<<< HEAD
名前付き関数と同様、クラスも名前を持つことができます。
クラス式に名前がある場合、そのクラス内部でのみ見えます:
@@ -217,6 +368,31 @@ alert(MyClass); // error, MyClass の名前はクラスの外からは見えま
```js run
function makeClass(phrase) {
// クラス定義とその返却
+=======
+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:
+
+```js run
+// "Named Class Expression"
+// (no such term in the spec, but that's similar to Named Function Expression)
+let User = class *!*MyClass*/!* {
+ sayHi() {
+ alert(MyClass); // MyClass name is visible only inside the class
+ }
+};
+
+new User().sayHi(); // works, shows MyClass definition
+
+alert(MyClass); // error, MyClass name isn't visible outside of the class
+```
+
+We can even make classes dynamically "on-demand", like this:
+
+```js run
+function makeClass(phrase) {
+ // declare a class and return it
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return class {
sayHi() {
alert(phrase);
@@ -224,24 +400,40 @@ function makeClass(phrase) {
};
}
+<<<<<<< HEAD
// 新しいクラスを作成
+=======
+// Create a new class
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let User = makeClass("Hello");
new User().sayHi(); // Hello
```
+<<<<<<< HEAD
### Getters/setters
リテラルオブジェクトのように、クラスも getters/setters, 算出プロパティなどを含めることができます。
これは、`get/set` を使用して実装された `user.name` の例です:
+=======
+## Getters/setters
+
+Just like literal objects, classes may include getters/setters, computed properties etc.
+
+Here's an example for `user.name` implemented using `get/set`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
constructor(name) {
+<<<<<<< HEAD
// setter を呼び出す
+=======
+ // invokes the setter
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this.name = name;
}
@@ -255,7 +447,11 @@ class User {
set name(value) {
*/!*
if (value.length < 4) {
+<<<<<<< HEAD
alert("Name too short.");
+=======
+ alert("Name is too short.");
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return;
}
this._name = value;
@@ -266,6 +462,7 @@ class User {
let user = new User("John");
alert(user.name); // John
+<<<<<<< HEAD
user = new User(""); // Name too short.
```
@@ -274,6 +471,16 @@ user = new User(""); // Name too short.
## 計算された名前(computed name)
これは括弧 `[...]` を使用した計算されたメソッド名の例です。
+=======
+user = new User(""); // Name is too short.
+```
+
+Technically, such class declaration works by creating getters and setters in `User.prototype`.
+
+## Computed names [...]
+
+Here's an example with a computed method name using brackets `[...]`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -289,6 +496,7 @@ class User {
new User().sayHi();
```
+<<<<<<< HEAD
このような特徴は、リテラルオブジェクトに似ているので、覚えやすいと思います。
## クラスフィールド
@@ -302,6 +510,21 @@ new User().sayHi();
"クラスフィールド" は任意のプロパティが追加できる構文です。
例えば、`class User` に `name` プロパティを追加しましょう。
+=======
+Such features are easy to remember, as they resemble that of literal objects.
+
+## Class fields
+
+```warn header="Old browsers may need a polyfill"
+Class fields are a recent addition to the language.
+```
+
+Previously, our classes only had methods.
+
+"Class fields" is a syntax that allows to add any properties.
+
+For instance, let's add `name` property to `class User`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -317,9 +540,15 @@ class User {
new User().sayHi(); // Hello, John!
```
+<<<<<<< HEAD
つまり、宣言の中で、" = " と記述するだけです。
クラスフィールドの重要な違いは、`User.prototype` ではなく、個々のオブジェクトにセットされることです。:
+=======
+So, we just write " = " in the declaration, and that's it.
+
+The important difference of class fields is that they are set on individual objects, not `User.prototype`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -333,7 +562,11 @@ alert(user.name); // John
alert(User.prototype.name); // undefined
```
+<<<<<<< HEAD
また、より複雑な式や関数呼び出しで値を代入することもできます。:
+=======
+We can also assign values using more complex expressions and function calls:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -347,6 +580,7 @@ alert(user.name); // John
```
+<<<<<<< HEAD
### クラスフィールドでバインドされたメソッドを作成する
章 でデモしたように、JavaScript での関数は動的な `this` を持ちます。これは呼び出しのコンテキストに依存します。
@@ -354,6 +588,15 @@ alert(user.name); // John
そのため、オブジェクトメソッドが渡され、別のコンテキストで呼び出された場合、`this` はもうそのオブジェクトの参照ではありません。
例えば、このコードは `undefined` になります:
+=======
+### Making bound methods with class fields
+
+As demonstrated in the chapter functions in JavaScript have a dynamic `this`. It depends on the context of the call.
+
+So if an object method is passed around and called in another context, `this` won't be a reference to its object any more.
+
+For instance, this code will show `undefined`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Button {
@@ -373,6 +616,7 @@ setTimeout(button.click, 1000); // undefined
*/!*
```
+<<<<<<< HEAD
問題は "`this` なし" で呼び出されたことです。
章 で議論したように、これを直す2つのアプローチがあります。:
@@ -381,6 +625,16 @@ setTimeout(button.click, 1000); // undefined
2. メソッドをオブジェクトにバインドする。 e.g. コンストラクタにて。
クラスフィールドは別の、すばらしい構文を提供します:
+=======
+The problem is called "losing `this`".
+
+There are two approaches to fixing it, as discussed in the chapter :
+
+1. Pass a wrapper-function, such as `setTimeout(() => button.click(), 1000)`.
+2. Bind the method to object, e.g. in the constructor.
+
+Class fields provide another, quite elegant syntax:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Button {
@@ -399,6 +653,7 @@ let button = new Button("hello");
setTimeout(button.click, 1000); // hello
```
+<<<<<<< HEAD
クラスフィールド `click = () => {...}` はオブジェクトごとに作られ、`Button` オブジェクトごとに別々の関数です。そして、`this` はそのオブジェクトを参照します。どこで `button.click` を渡しても、`this` は常に正しい値になります。
これはイベントリスナーなど、ブラウザ環境で特に役立ちます。
@@ -421,10 +676,40 @@ class MyClass {
set something(...) {} // setter
[Symbol.iterator]() {} // 計算された名前のメソッド (ここではシンボル)
+=======
+The class field `click = () => {...}` is created on a per-object basis, there's a separate function for each `Button` object, with `this` inside it referencing that object. We can pass `button.click` around anywhere, and the value of `this` will always be correct.
+
+That's especially useful in browser environment, for event listeners.
+
+## Summary
+
+The basic class syntax looks like this:
+
+```js
+class MyClass {
+ prop = value; // property
+
+ constructor(...) { // constructor
+ // ...
+ }
+
+ method(...) {} // method
+
+ get something(...) {} // getter method
+ set something(...) {} // setter method
+
+ [Symbol.iterator]() {} // method with computed name (symbol here)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// ...
}
```
+<<<<<<< HEAD
`MyClass` は技術的には関数(`constructor` として提供)で、メソッド、getter / setter は `MyClass.prototype` に記述されます。
次の章では、継承など他の機能を含め、クラスにてより詳しく学びます。
+=======
+`MyClass` is technically a function (the one that we provide as `constructor`), while methods, getters and setters are written to `MyClass.prototype`.
+
+In the next chapters we'll learn more about classes, including inheritance and other features.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/02-class-inheritance/1-class-constructor-error/task.md b/1-js/09-classes/02-class-inheritance/1-class-constructor-error/task.md
index b4be5c946f..198a275e74 100644
--- a/1-js/09-classes/02-class-inheritance/1-class-constructor-error/task.md
+++ b/1-js/09-classes/02-class-inheritance/1-class-constructor-error/task.md
@@ -2,12 +2,20 @@ importance: 5
---
+<<<<<<< HEAD
# インスタンス作成エラー
これは `Animal` を拡張した `Rabbit` のコードです。
残念なことに、`Rabbit` オブジェクトを作ることができません。何が間違っているでしょう?直してください。
+=======
+# Error creating an instance
+
+Here's the code with `Rabbit` extending `Animal`.
+
+Unfortunately, `Rabbit` objects can't be created. What's wrong? Fix it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -25,7 +33,11 @@ class Rabbit extends Animal {
}
*!*
+<<<<<<< HEAD
let rabbit = new Rabbit("White Rabbit"); // エラー: 定義されていません
+=======
+let rabbit = new Rabbit("White Rabbit"); // Error: this is not defined
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(rabbit.name);
```
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.md b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.md
index e69de29bb2..dcb4ffe59a 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.md
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.md
@@ -0,0 +1 @@
+[js src="solution.view/extended-clock.js"]
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/clock.js b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/clock.js
index 8009273e3f..7918cfceed 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/clock.js
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/clock.js
@@ -1,9 +1,9 @@
class Clock {
constructor({ template }) {
- this._template = template;
+ this.template = template;
}
- _render() {
+ render() {
let date = new Date();
let hours = date.getHours();
@@ -15,7 +15,7 @@ class Clock {
let secs = date.getSeconds();
if (secs < 10) secs = '0' + secs;
- let output = this._template
+ let output = this.template
.replace('h', hours)
.replace('m', mins)
.replace('s', secs);
@@ -24,11 +24,18 @@ class Clock {
}
stop() {
- clearInterval(this._timer);
+ clearInterval(this.timer);
}
start() {
- this._render();
- this._timer = setInterval(() => this._render(), 1000);
+ this.render();
+ this.timer = setInterval(() => this.render(), 1000);
}
}
+<<<<<<< HEAD
+
+
+let clock = new Clock({template: 'h:m:s'});
+clock.start();
+=======
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/extended-clock.js b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/extended-clock.js
index 4eb12381f9..3de442f3f9 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/extended-clock.js
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/extended-clock.js
@@ -1,6 +1,7 @@
class ExtendedClock extends Clock {
constructor(options) {
super(options);
+<<<<<<< HEAD
let { precision=1000 } = options;
this._precision = precision;
}
@@ -8,5 +9,14 @@ class ExtendedClock extends Clock {
start() {
this._render();
this._timer = setInterval(() => this._render(), this._precision);
+=======
+ let { precision = 1000 } = options;
+ this.precision = precision;
+ }
+
+ start() {
+ this.render();
+ this.timer = setInterval(() => this.render(), this.precision);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/index.html b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/index.html
index 7ac1db7143..aec9eb7f98 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/index.html
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/index.html
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
@@ -21,3 +22,16 @@
+=======
+
+
+
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/clock.js b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/clock.js
index 8009273e3f..d701c0caeb 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/clock.js
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/clock.js
@@ -1,9 +1,9 @@
class Clock {
constructor({ template }) {
- this._template = template;
+ this.template = template;
}
- _render() {
+ render() {
let date = new Date();
let hours = date.getHours();
@@ -15,7 +15,7 @@ class Clock {
let secs = date.getSeconds();
if (secs < 10) secs = '0' + secs;
- let output = this._template
+ let output = this.template
.replace('h', hours)
.replace('m', mins)
.replace('s', secs);
@@ -24,11 +24,11 @@ class Clock {
}
stop() {
- clearInterval(this._timer);
+ clearInterval(this.timer);
}
start() {
- this._render();
- this._timer = setInterval(() => this._render(), 1000);
+ this.render();
+ this.timer = setInterval(() => this.render(), 1000);
}
}
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/index.html b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/index.html
index b48a2a0074..5823942eb8 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/index.html
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/source.view/index.html
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
@@ -32,3 +33,25 @@
+=======
+
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/task.md b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/task.md
index 29be5d86bb..6265e12bf9 100644
--- a/1-js/09-classes/02-class-inheritance/2-clock-class-extended/task.md
+++ b/1-js/09-classes/02-class-inheritance/2-clock-class-extended/task.md
@@ -2,6 +2,7 @@ importance: 5
---
+<<<<<<< HEAD
# 拡張された時計
私たちは `Clock` クラスを持っています。今のところ、毎秒時間を表示します。
@@ -10,3 +11,16 @@ importance: 5
- あなたのコードはファイル `extended-clock.js` にしてください。
- オジリナルの `clock.js` は変更しないでください。それを拡張してください。
+=======
+# Extended clock
+
+We've got a `Clock` class. As of now, it prints the time every second.
+
+
+[js src="source.view/clock.js"]
+
+Create a new class `ExtendedClock` that inherits from `Clock` and adds the parameter `precision` -- the number of `ms` between "ticks". Should be `1000` (1 second) by default.
+
+- Your code should be in the file `extended-clock.js`
+- Don't modify the original `clock.js`. Extend it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/02-class-inheritance/article.md b/1-js/09-classes/02-class-inheritance/article.md
index 2a6a7f0930..7b9721cfcd 100644
--- a/1-js/09-classes/02-class-inheritance/article.md
+++ b/1-js/09-classes/02-class-inheritance/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# クラスの継承
クラスの継承は、あるクラスが別のクラスを拡張するための方法です。
@@ -8,6 +9,17 @@
## "extends" キーワード
クラス `Animal` があるとします:
+=======
+# Class inheritance
+
+Class inheritance is a way for one class to extend another class.
+
+So we can create new functionality on top of the existing.
+
+## The "extends" keyword
+
+Let's say we have class `Animal`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class Animal {
@@ -16,18 +28,27 @@ class Animal {
this.name = name;
}
run(speed) {
+<<<<<<< HEAD
this.speed += speed;
+=======
+ this.speed = speed;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(`${this.name} runs with speed ${this.speed}.`);
}
stop() {
this.speed = 0;
+<<<<<<< HEAD
alert(`${this.name} stopped.`);
+=======
+ alert(`${this.name} stands still.`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
let animal = new Animal("My animal");
```
+<<<<<<< HEAD
これは、`animal` オブジェクトと `Animal` クラスを、グラフィカルに表現したものです。:

@@ -39,6 +60,19 @@ let animal = new Animal("My animal");
別のクラスを拡張する構文は `class Child extends Parent` です。
`Animal` を継承した `class Rabbit` を作成しましょう。:
+=======
+Here's how we can represent `animal` object and `Animal` class graphically:
+
+
+
+...And we would like to create another `class Rabbit`.
+
+As rabbits are animals, `Rabbit` class should be based on `Animal`, have access to animal methods, so that rabbits can do what "generic" animals can do.
+
+The syntax to extend another class is: `class Child extends Parent`.
+
+Let's create `class Rabbit` that inherits from `Animal`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
*!*
@@ -55,6 +89,7 @@ rabbit.run(5); // White Rabbit runs with speed 5.
rabbit.hide(); // White Rabbit hides!
```
+<<<<<<< HEAD
`Rabbit` クラスのオブジェクトは、`rabbit.hide()` のように `Rabbit` のメソッドと、`rabbit.run()` のように `Animal` メソッド両方が利用できます。
内部では、`extends` キーワードは、以前からあるプロトタイプの仕組みを使用して動作しています。`Rabbit.prototype.[[Prototype]]` を `Animal.prototype` にセットします。そのため、`Rabbit.prototype` でメソッドが見つからない場合には、JavaScript は `Animal.prototype` から取得します。
@@ -72,12 +107,36 @@ rabbit.hide(); // White Rabbit hides!
クラス構文では単にクラスではなく、`extends` の後に任意の式を指定することができます。
例えば、親クラスを生成する関数呼び出します:
+=======
+Object of `Rabbit` class have access both to `Rabbit` methods, such as `rabbit.hide()`, and also to `Animal` methods, such as `rabbit.run()`.
+
+Internally, `extends` keyword works using the good old prototype mechanics. It sets `Rabbit.prototype.[[Prototype]]` to `Animal.prototype`. So, if a method is not found in `Rabbit.prototype`, JavaScript takes it from `Animal.prototype`.
+
+
+
+For instance, to find `rabbit.run` method, the engine checks (bottom-up on the picture):
+1. The `rabbit` object (has no `run`).
+2. Its prototype, that is `Rabbit.prototype` (has `hide`, but not `run`).
+3. Its prototype, that is (due to `extends`) `Animal.prototype`, that finally has the `run` method.
+
+As we can recall from the chapter , JavaScript itself uses prototypal inheritance for built-in objects. E.g. `Date.prototype.[[Prototype]]` is `Object.prototype`. That's why dates have access to 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`.
+
+For instance, a function call that generates the parent class:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function f(phrase) {
return class {
+<<<<<<< HEAD
sayHi() { alert(phrase) }
}
+=======
+ sayHi() { alert(phrase); }
+ };
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
*!*
@@ -86,6 +145,7 @@ class User extends f("Hello") {}
new User().sayHi(); // Hello
```
+<<<<<<< HEAD
ここでは、 `class User` は `f("Hello")` の結果を継承しています。
多くの条件に依存したクラスを生成するために関数を使用し、それを継承するといった高度なプログラミングパターンに対して役立つ場合があります。
@@ -96,16 +156,34 @@ new User().sayHi(); // Hello
では、前に進めてメソッドをオーバライドをしてみましょう。デフォルトでは、`class Rabbit` では指定されておらず、`class Animal` から直接 "そのまま" 取得しています。
ですが、`Rabbit` で自身の `stop` を指定すると、代わりにそれが使われます。:
+=======
+Here `class User` inherits from the result of `f("Hello")`.
+
+That may be useful for advanced programming patterns when we use functions to generate classes depending on many conditions and can inherit from them.
+````
+
+## Overriding a method
+
+Now let's move forward and override a method. By default, all methods that are not specified in `class Rabbit` are taken directly "as is" from `class Animal`.
+
+But if we specify our own method in `Rabbit`, such as `stop()` then it will be used instead:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class Rabbit extends Animal {
stop() {
+<<<<<<< HEAD
// ...class Animal の stop() の代わりに
// rabbit.stop() で利用されます
+=======
+ // ...now this will be used for rabbit.stop()
+ // instead of stop() from class Animal
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
通常は親メソッドを完全に置き換えるのではなく、その上に機能の微調整または拡張を行うことを望みます。メソッド内で何かをしますが、その前後または処理中に親メソッドを呼び出します。
クラスはそのために `"super"` キーワードを提供しています。
@@ -114,6 +192,16 @@ class Rabbit extends Animal {
- `super(...)` は親のコンストラクタを呼び出します(コンストラクタの内側でのみ)。
例えば、うさぎ(rabbit)が止まったとき自動的に隠れさせます。:
+=======
+Usually, however, we don't want to totally replace a parent method, but rather to build on top of it to 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.
+
+- `super.method(...)` to call a parent method.
+- `super(...)` to call a parent constructor (inside our constructor only).
+
+For instance, let our rabbit autohide when stopped:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -124,13 +212,21 @@ class Animal {
}
run(speed) {
+<<<<<<< HEAD
this.speed += speed;
+=======
+ this.speed = speed;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(`${this.name} runs with speed ${this.speed}.`);
}
stop() {
this.speed = 0;
+<<<<<<< HEAD
alert(`${this.name} stopped.`);
+=======
+ alert(`${this.name} stands still.`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
@@ -142,8 +238,13 @@ class Rabbit extends Animal {
*!*
stop() {
+<<<<<<< HEAD
super.stop(); // 親の stop 呼び出し
this.hide(); // その後隠す
+=======
+ super.stop(); // call parent stop
+ this.hide(); // and then hide
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
*/!*
}
@@ -151,6 +252,7 @@ class Rabbit extends Animal {
let rabbit = new Rabbit("White Rabbit");
rabbit.run(5); // White Rabbit runs with speed 5.
+<<<<<<< HEAD
rabbit.stop(); // White Rabbit stopped. White rabbit hides!
```
@@ -164,11 +266,31 @@ rabbit.stop(); // White Rabbit stopped. White rabbit hides!
class Rabbit extends Animal {
stop() {
setTimeout(() => super.stop(), 1000); // 1秒後、親の stop を実行
+=======
+rabbit.stop(); // White Rabbit stands still. White Rabbit hides!
+```
+
+Now `Rabbit` has the `stop` method that calls the parent `super.stop()` in the process.
+
+````smart header="Arrow functions have no `super`"
+As was mentioned in the chapter , arrow functions do not have `super`.
+
+If accessed, it's taken from the outer function. For instance:
+
+```js
+class Rabbit extends Animal {
+ stop() {
+ setTimeout(() => super.stop(), 1000); // call parent stop after 1sec
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
アロー関数での `super` は、 `stop()` 内での `super` と同じです。なので、意図通りに動きます。以下のように "通常の" 関数を指定するとエラーになります。:
+=======
+The `super` in the arrow function is the same as in `stop()`, so it works as intended. If we specified a "regular" function here, there would be an error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// Unexpected super
@@ -176,6 +298,7 @@ setTimeout(function() { super.stop() }, 1000);
```
````
+<<<<<<< HEAD
## コンストラクタのオーバライド
@@ -188,6 +311,19 @@ setTimeout(function() { super.stop() }, 1000);
```js
class Rabbit extends Animal {
// 独自のコンストラクタを持たないクラスを拡張するために生成されます
+=======
+## Overriding constructor
+
+With constructors it gets a little bit tricky.
+
+Until now, `Rabbit` did not have its own `constructor`.
+
+According to the [specification](https://tc39.github.io/ecma262/#sec-runtime-semantics-classdefinitionevaluation), if a class extends another class and has no `constructor`, then the following "empty" `constructor` is generated:
+
+```js
+class Rabbit extends Animal {
+ // generated for extending classes without own constructors
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
constructor(...args) {
super(...args);
@@ -196,9 +332,15 @@ class Rabbit extends Animal {
}
```
+<<<<<<< HEAD
ご覧の通り、基本的にはすべての引数を渡して親の `constructor` を呼び出します。それは自身のコンストラクタを書いていない場合に起こります。
では、カスタムのコンストラクタを `Rabbit` に追加してみましょう。それは `name` に加えて `earLength` を指定します。:
+=======
+As we can see, it basically calls the parent `constructor` passing it all the arguments. That happens if we don't write a constructor of our own.
+
+Now let's add a custom constructor to `Rabbit`. It will specify the `earLength` in addition to `name`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -223,6 +365,7 @@ class Rabbit extends Animal {
}
*!*
+<<<<<<< HEAD
// 動作しません!
let rabbit = new Rabbit("White Rabbit", 10); // Error: this は定義されていません
*/!*
@@ -248,6 +391,33 @@ JavaScriptでは、継承しているクラスのコンストラクタ関数(い
なので、親(元になる)コンストラクタを実行するために、派生コンスタクタは `super` の呼び出しが必要になります。そうしないと、`this` のオブジェクトは生成されないからです。結果、エラーになるでしょう。
`Rabbit` コンストラクタを動作させるために、`this` を使う前に `super()` を呼びます:
+=======
+// Doesn't work!
+let rabbit = new Rabbit("White Rabbit", 10); // Error: this is not defined.
+*/!*
+```
+
+Whoops! We've got an error. Now we can't create rabbits. What went wrong?
+
+The short answer is:
+
+- **Constructors in inheriting classes must call `super(...)`, and (!) do it before using `this`.**
+
+...But why? What's going on here? Indeed, the requirement seems strange.
+
+Of course, there's an explanation. Let's get into details, so you'll really understand what's going on.
+
+In JavaScript, there's a distinction between a constructor function of an inheriting class (so-called "derived constructor") and other functions. A derived constructor has a special internal property `[[ConstructorKind]]:"derived"`. That's a special internal label.
+
+That label affects its behavior with `new`.
+
+- When a regular function is executed with `new`, 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 a derived constructor must call `super` in order to execute its parent (base) constructor, otherwise the object for `this` won't be created. And we'll get an error.
+
+For the `Rabbit` constructor to work, it needs to call `super()` before using `this`, like here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -273,13 +443,18 @@ class Rabbit extends Animal {
}
*!*
+<<<<<<< HEAD
// 今は問題ありません
+=======
+// now fine
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let rabbit = new Rabbit("White Rabbit", 10);
alert(rabbit.name); // White Rabbit
alert(rabbit.earLength); // 10
*/!*
```
+<<<<<<< HEAD
### クラスフィールドのオーバーライド: a tricky note
@@ -297,6 +472,23 @@ alert(rabbit.earLength); // 10
ですが、親のコンストラクタでオーバーライドされたフィールドにアクセスする際、多くの他のプログラミング言語とは大きく異なる、トリッキーな振る舞いがあります。
この例を考えます:
+=======
+### Overriding class fields: a tricky note
+
+```warn header="Advanced note"
+This note assumes you have a certain experience with classes, maybe in other programming languages.
+
+It provides better insight into the language and also explains the behavior that might be a source of bugs (but not very often).
+
+If you find it difficult to understand, just go on, continue reading, then return to it some time later.
+```
+
+We can override not only methods, but also class fields.
+
+Although, there's a tricky behavior when we access an overridden field in parent constructor, quite different from most other programming languages.
+
+Consider this example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -317,6 +509,7 @@ new Rabbit(); // animal
*/!*
```
+<<<<<<< HEAD
ここでは、クラス `Rabbit` は `Animal` を拡張しており、`name` フィールドを自身の値としてオーバーライドしています。
`Rabbit` には自身のコンストラクタはないので、`Animal` コンストラクタが呼ばれます。
@@ -334,11 +527,34 @@ new Rabbit(); // animal
```js run
class Animal {
showName() { // this.name = 'animal' の代わり
+=======
+Here, class `Rabbit` extends `Animal` and overrides the `name` field with its own value.
+
+There's no own constructor in `Rabbit`, so `Animal` constructor is called.
+
+What's interesting is that in both cases: `new Animal()` and `new Rabbit()`, the `alert` in the line `(*)` shows `animal`.
+
+**In other words, the parent constructor always uses its own field value, not the overridden one.**
+
+What's odd about it?
+
+If it's not clear yet, please compare with methods.
+
+Here's the same code, but instead of `this.name` field we call `this.showName()` method:
+
+```js run
+class Animal {
+ showName() { // instead of this.name = 'animal'
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert('animal');
}
constructor() {
+<<<<<<< HEAD
this.showName(); // alert(this.name); の代わり
+=======
+ this.showName(); // instead of alert(this.name);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
@@ -354,6 +570,7 @@ new Rabbit(); // rabbit
*/!*
```
+<<<<<<< HEAD
注目してください: 出力結果は異なります。
そして、これは自然に期待しているものです。親コンストラクタが派生クラスで呼び出されるとき、オーバーライドされたメソッドが使用されます。
@@ -398,12 +615,61 @@ new Rabbit(); // rabbit
詳細を知る必要がなければ、このパートをスキップして `[[HomeObject]]` サブセクションに進んでください。特に問題はありません。ここは物事を深く理解することに興味がある場合に呼んでください。
以下の例で、`rabbit.__proto__ = animal` です。`rabbit.eat()` で、`this.__proto__` を使用して、`animal.eat()` メソッドを呼び出します:
+=======
+Please note: now the output is different.
+
+And that's what we naturally expect. When the parent constructor is called in the derived class, it uses the overridden method.
+
+...But for class fields it's not so. As said, the parent constructor always uses the parent field.
+
+Why is there a difference?
+
+Well, the reason is the field initialization order. The class field is initialized:
+- Before constructor for the base class (that doesn't extend anything),
+- Immediately after `super()` for the derived class.
+
+In our case, `Rabbit` is the derived class. There's no `constructor()` in it. As said previously, that's the same as if there was an empty constructor with only `super(...args)`.
+
+So, `new Rabbit()` calls `super()`, thus executing the parent constructor, and (per the rule for derived classes) only after that its class fields are initialized. At the time of the parent constructor execution, there are no `Rabbit` class fields yet, that's why `Animal` fields are used.
+
+This subtle difference between fields and methods is specific to JavaScript.
+
+Luckily, this behavior only reveals itself if an overridden field is used in the parent constructor. Then it may be difficult to understand what's going on, so we're explaining it here.
+
+If it becomes a problem, one can fix it by using methods or getters/setters instead of fields.
+
+## 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 along 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 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__`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
name: "Animal",
eat() {
+<<<<<<< HEAD
alert(this.name + " eats.");
+=======
+ alert(`${this.name} eats.`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
@@ -412,7 +678,11 @@ let rabbit = {
name: "Rabbit",
eat() {
*!*
+<<<<<<< HEAD
// これがおそらく super.eat() が動作する方法です
+=======
+ // that's how super.eat() could presumably work
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this.__proto__.eat.call(this); // (*)
*/!*
}
@@ -421,24 +691,40 @@ let rabbit = {
rabbit.eat(); // Rabbit eats.
```
+<<<<<<< HEAD
行 `(*)` でプロトタイプ(`animal`) から `eat` を取り、現在のオブジェクトコンテキストでそれを呼び出します。`.call(this)` はここでは重要であることに注意してください。なぜなら、シンプルな `this.__proto__.eat()` は現在のオブジェクトではなくプロトタイプのコンテキストで親の `eat` を実行するためです。
また、上のコードは実際に期待通り動作します: 正しい `alert` になります。
今度はもう1つのオブジェクトをチェーンに追加しましょう。 どのように壊れるかを見てみます:
+=======
+At the line `(*)` we take `eat` from the prototype (`animal`) and call it in the context of the current object. Please note that `.call(this)` is important here, because a simple `this.__proto__.eat()` would execute parent `eat` in the context of the prototype, not the current object.
+
+And in the code above it actually works as intended: we have the correct `alert`.
+
+Now let's add one more object to the chain. We'll see how things break:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
name: "Animal",
eat() {
+<<<<<<< HEAD
alert(this.name + " eats.");
+=======
+ alert(`${this.name} eats.`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
let rabbit = {
__proto__: animal,
eat() {
+<<<<<<< HEAD
// ...bounce around rabbit-style 親 (animal) メソッドを呼び出す
+=======
+ // ...bounce around rabbit-style and call parent (animal) method
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this.__proto__.eat.call(this); // (*)
}
};
@@ -446,12 +732,17 @@ let rabbit = {
let longEar = {
__proto__: rabbit,
eat() {
+<<<<<<< HEAD
// ...do something with long ears 親 (rabbit) メソッドを呼び出す
+=======
+ // ...do something with long ears and call parent (rabbit) method
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this.__proto__.eat.call(this); // (**)
}
};
*!*
+<<<<<<< HEAD
longEar.eat(); // Error: 最大呼び出しスタックサイズを超えました
*/!*
```
@@ -499,19 +790,77 @@ longEar.eat(); // Error: 最大呼び出しスタックサイズを超えまし
そして、`super` はこれを使って親のプロトタイプとメソッドメソッドを解決しましま。
最初のオブジェクトで、それがどのように動くのか見てみましょう:
+=======
+longEar.eat(); // Error: Maximum call stack size exceeded
+*/!*
+```
+
+The code doesn't work anymore! We can see the error trying to call `longEar.eat()`.
+
+It may be not that obvious, but if we trace `longEar.eat()` call, then we can see why. In both lines `(*)` and `(**)` the value of `this` is the current object (`longEar`). That's essential: all object methods get the current object as `this`, not a prototype or something.
+
+So, in both lines `(*)` and `(**)` the value of `this.__proto__` is exactly the same: `rabbit`. They both call `rabbit.eat` without going up the chain in the endless loop.
+
+Here's the picture of what happens:
+
+
+
+1. Inside `longEar.eat()`, the line `(**)` calls `rabbit.eat` providing it with `this=longEar`.
+ ```js
+ // inside longEar.eat() we have this = longEar
+ this.__proto__.eat.call(this) // (**)
+ // becomes
+ longEar.__proto__.eat.call(this)
+ // that is
+ rabbit.eat.call(this);
+ ```
+2. Then in the line `(*)` of `rabbit.eat`, we'd like to pass the call even higher in the chain, but `this=longEar`, so `this.__proto__.eat` is again `rabbit.eat`!
+
+ ```js
+ // inside rabbit.eat() we also have this = longEar
+ this.__proto__.eat.call(this) // (*)
+ // becomes
+ longEar.__proto__.eat.call(this)
+ // or (again)
+ rabbit.eat.call(this);
+ ```
+
+3. ...So `rabbit.eat` calls itself in the endless loop, because it can't ascend any further.
+
+The problem can't be solved by using `this` alone.
+
+### `[[HomeObject]]`
+
+To provide the solution, JavaScript adds one more special internal property for functions: `[[HomeObject]]`.
+
+When a function is specified as a class or object method, its `[[HomeObject]]` property becomes that object.
+
+Then `super` uses it to resolve the parent prototype and its methods.
+
+Let's see how it works, first with plain objects:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
name: "Animal",
+<<<<<<< HEAD
eat() { // [[HomeObject]] == animal
alert(this.name + " eats.");
+=======
+ eat() { // animal.eat.[[HomeObject]] == animal
+ alert(`${this.name} eats.`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
let rabbit = {
__proto__: animal,
name: "Rabbit",
+<<<<<<< HEAD
eat() { // [[HomeObject]] == rabbit
+=======
+ eat() { // rabbit.eat.[[HomeObject]] == rabbit
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
super.eat();
}
};
@@ -519,17 +868,26 @@ let rabbit = {
let longEar = {
__proto__: rabbit,
name: "Long Ear",
+<<<<<<< HEAD
eat() { // [[HomeObject]] == longEar
+=======
+ eat() { // longEar.eat.[[HomeObject]] == longEar
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
super.eat();
}
};
*!*
+<<<<<<< HEAD
// ただしく機能します
+=======
+// works correctly
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
longEar.eat(); // Long Ear eats.
*/!*
```
+<<<<<<< HEAD
`[[HomeObject]]` のより、意図したとおりに動作します。`longEar.eat` のようなメソッドは、その `[[HomeObject]]` を知っており、そのプロトタイプから親のメソッドを取得します。`this` を使用することなく。
### メソッドは "自由" ではありません
@@ -541,6 +899,19 @@ longEar.eat(); // Long Ear eats.
`[[HomeObject]]` が使用される言語での唯一の場所が `super` です。したがって、メソッドが `super` を使用しない場合、メソッドは以前として自由とみなせ、オブジェクト間でコピーできます。しかし、`super` があると、うまくいかない可能性があります。
これはコピー後の上手く行かない `super` の結果のデモです:
+=======
+It works as intended, due to `[[HomeObject]]` mechanics. A method, such as `longEar.eat`, knows its `[[HomeObject]]` and takes the parent method from its prototype. Without any use of `this`.
+
+### Methods are not "free"
+
+As we've known before, generally functions are "free", not bound to objects in JavaScript. So they can be copied between objects and called with another `this`.
+
+The very existence of `[[HomeObject]]` violates that principle, because methods remember their objects. `[[HomeObject]]` can't be changed, so this bond is forever.
+
+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` result after copying:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let animal = {
@@ -549,7 +920,11 @@ let animal = {
}
};
+<<<<<<< HEAD
// rabbit は animal を継承
+=======
+// rabbit inherits from animal
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let rabbit = {
__proto__: animal,
sayHi() {
@@ -563,7 +938,11 @@ let plant = {
}
};
+<<<<<<< HEAD
// tree は plant を継承
+=======
+// tree inherits from plant
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let tree = {
__proto__: plant,
*!*
@@ -576,6 +955,7 @@ tree.sayHi(); // I'm an animal (?!?)
*/!*
```
+<<<<<<< HEAD
`tree.sayHi()` の呼び出しは、"I'm an animal" を表示します。これは間違いです。
理由は簡単です:
@@ -598,6 +978,30 @@ tree.sayHi(); // I'm an animal (?!?)
```js run
let animal = {
eat: function() { // 短縮構文: eat() {...} にする必要があります
+=======
+A call to `tree.sayHi()` shows "I'm an animal". Definitely wrong.
+
+The reason is simple:
+- In the line `(*)`, the method `tree.sayHi` was copied from `rabbit`. Maybe we just wanted to avoid code duplication?
+- 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`.
+
+Here's the diagram of what happens:
+
+
+
+### Methods, not function properties
+
+`[[HomeObject]]` is defined for methods both in classes and in plain objects. But for objects, methods must be specified exactly as `method()`, not as `"method: function()"`.
+
+The difference may be non-essential for us, but it's important for JavaScript.
+
+In the example below a non-method syntax is used for comparison. `[[HomeObject]]` property is not set and the inheritance doesn't work:
+
+```js run
+let animal = {
+ eat: function() { // intentionally writing like this instead of eat() {...
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// ...
}
};
@@ -610,6 +1014,7 @@ let rabbit = {
};
*!*
+<<<<<<< HEAD
rabbit.eat(); // super 呼び出しエラー([[HomeObject]] が無いため)
*/!*
```
@@ -628,3 +1033,23 @@ rabbit.eat(); // super 呼び出しエラー([[HomeObject]] が無いため)
また:
- アロー関数は独自の `this` や `super` を持っていないので、周囲の文脈に透過的にフィットします。
+=======
+rabbit.eat(); // Error calling super (because there's no [[HomeObject]])
+*/!*
+```
+
+## Summary
+
+1. To extend a class: `class Child extends Parent`:
+ - That means `Child.prototype.__proto__` will be `Parent.prototype`, so methods are inherited.
+2. When overriding a constructor:
+ - We must call parent constructor as `super()` in `Child` constructor before using `this`.
+3. When overriding another method:
+ - We can use `super.method()` in a `Child` method to call `Parent` method.
+4. Internals:
+ - Methods remember their class/object in the internal `[[HomeObject]]` property. That's how `super` resolves parent methods.
+ - So it's not safe to copy a method with `super` from one object to another.
+
+Also:
+- Arrow functions don't have their own `this` or `super`, so they transparently fit into the surrounding context.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/03-static-properties-methods/3-class-extend-object/rabbit-extends-object.svg b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/rabbit-extends-object.svg
new file mode 100644
index 0000000000..915ab9aa64
--- /dev/null
+++ b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/rabbit-extends-object.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/1-js/09-classes/03-static-properties-methods/3-class-extend-object/solution.md b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/solution.md
new file mode 100644
index 0000000000..cb9829ce05
--- /dev/null
+++ b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/solution.md
@@ -0,0 +1,81 @@
+First, let's see why the latter code doesn't work.
+
+The reason becomes obvious if we try to run it. An inheriting class constructor must call `super()`. Otherwise `"this"` won't be "defined".
+
+So here's the fix:
+
+```js run
+class Rabbit extends Object {
+ constructor(name) {
+*!*
+ super(); // need to call the parent constructor when inheriting
+*/!*
+ this.name = name;
+ }
+}
+
+let rabbit = new Rabbit("Rab");
+
+alert( rabbit.hasOwnProperty('name') ); // true
+```
+
+But that's not all yet.
+
+Even after the fix, there's still an important difference between `"class Rabbit extends Object"` and `class Rabbit`.
+
+As we know, the "extends" syntax sets up two prototypes:
+
+1. Between `"prototype"` of the constructor functions (for methods).
+2. Between the constructor functions themselves (for static methods).
+
+In the case of `class Rabbit extends Object` it means:
+
+```js run
+class Rabbit extends Object {}
+
+alert( Rabbit.prototype.__proto__ === Object.prototype ); // (1) true
+alert( Rabbit.__proto__ === Object ); // (2) true
+```
+
+So `Rabbit` now provides access to the static methods of `Object` via `Rabbit`, like this:
+
+```js run
+class Rabbit extends Object {}
+
+*!*
+// normally we call Object.getOwnPropertyNames
+alert ( Rabbit.getOwnPropertyNames({a: 1, b: 2})); // a,b
+*/!*
+```
+
+But if we don't have `extends Object`, then `Rabbit.__proto__` is not set to `Object`.
+
+Here's the demo:
+
+```js run
+class Rabbit {}
+
+alert( Rabbit.prototype.__proto__ === Object.prototype ); // (1) true
+alert( Rabbit.__proto__ === Object ); // (2) false (!)
+alert( Rabbit.__proto__ === Function.prototype ); // as any function by default
+
+*!*
+// error, no such function in Rabbit
+alert ( Rabbit.getOwnPropertyNames({a: 1, b: 2})); // Error
+*/!*
+```
+
+So `Rabbit` doesn't provide access to static methods of `Object` in that case.
+
+By the way, `Function.prototype` also has "generic" function methods, like `call`, `bind` etc. They are ultimately available in both cases, because for the built-in `Object` constructor, `Object.__proto__ === Function.prototype`.
+
+Here's the picture:
+
+
+
+So, to put it short, there are two differences:
+
+| class Rabbit | class Rabbit extends Object |
+|--------------|------------------------------|
+| -- | needs to call `super()` in constructor |
+| `Rabbit.__proto__ === Function.prototype` | `Rabbit.__proto__ === Object` |
diff --git a/1-js/09-classes/03-static-properties-methods/3-class-extend-object/task.md b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/task.md
new file mode 100644
index 0000000000..1d0f98a74e
--- /dev/null
+++ b/1-js/09-classes/03-static-properties-methods/3-class-extend-object/task.md
@@ -0,0 +1,42 @@
+importance: 3
+
+---
+
+# Class extends Object?
+
+As we know, all objects normally inherit from `Object.prototype` and get access to "generic" object methods like `hasOwnProperty` etc.
+
+For instance:
+
+```js run
+class Rabbit {
+ constructor(name) {
+ this.name = name;
+ }
+}
+
+let rabbit = new Rabbit("Rab");
+
+*!*
+// hasOwnProperty method is from Object.prototype
+alert( rabbit.hasOwnProperty('name') ); // true
+*/!*
+```
+
+But if we spell it out explicitly like `"class Rabbit extends Object"`, then the result would be different from a simple `"class Rabbit"`?
+
+What's the difference?
+
+Here's an example of such code (it doesn't work -- why? fix it?):
+
+```js
+class Rabbit extends Object {
+ constructor(name) {
+ this.name = name;
+ }
+}
+
+let rabbit = new Rabbit("Rab");
+
+alert( rabbit.hasOwnProperty('name') ); // Error
+```
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 caef4925f6..00c73914e3 100644
--- a/1-js/09-classes/03-static-properties-methods/article.md
+++ b/1-js/09-classes/03-static-properties-methods/article.md
@@ -1,8 +1,17 @@
+<<<<<<< HEAD
# 静的(static)プロパティとメソッド
クラス全体にメソッドを割り当てることもできます。このようなメソッドは _static(静的)_ と呼ばれます。
クラス宣言の中では、次のように `static` キーワードを付けます。
+=======
+
+# Static properties and methods
+
+We can also assign a method to the class as a whole. Such methods are called *static*.
+
+In a class declaration, they are prepended by `static` keyword, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class User {
@@ -16,18 +25,28 @@ class User {
User.staticMethod(); // true
```
+<<<<<<< HEAD
これは、実際にはプロパティとして直接割り当てるのと同じことをします。:
```js
class User {}
User.staticMethod = function () {
+=======
+That actually does the same as assigning it as a property directly:
+
+```js run
+class User { }
+
+User.staticMethod = function() {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(this === User);
};
User.staticMethod(); // true
```
+<<<<<<< HEAD
`User.staticMethod()` 内の `this` の値はクラスコンストラクタ `User` 自身("ドットの前のオブジェクト" ルール)です。
通常 static メソッドは、クラスには属するが、特定のオブジェクトには属さない関数を実装するのに使用されます。
@@ -35,6 +54,15 @@ User.staticMethod(); // true
例えば、`Article` オブジェクトがあり、それらを比較するための関数が必要とします。
自然な解決策は、静的メソッド `Article.compare` を追加することです。:
+=======
+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 as a whole, but not to any particular object of it.
+
+For instance, we have `Article` objects and need a function to compare them.
+
+A natural solution would be to add `Article.compare` static method:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Article {
@@ -52,8 +80,13 @@ class Article {
// usage
let articles = [
+<<<<<<< HEAD
new Article("Mind", new Date(2019, 1, 1)),
new Article("Body", new Date(2019, 0, 1)),
+=======
+ new Article("HTML", new Date(2019, 1, 1)),
+ new Article("CSS", new Date(2019, 0, 1)),
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
new Article("JavaScript", new Date(2019, 11, 1))
];
@@ -61,6 +94,7 @@ let articles = [
articles.sort(Article.compare);
*/!*
+<<<<<<< HEAD
alert( articles[0].title ); // Body
```
@@ -77,6 +111,24 @@ alert( articles[0].title ); // Body
最初の方法はコンストラクタで実装することができます。そして、2 つ目の方法としてはクラスの静的メソッドを作ることができます。
ここでの `Article.createTodays()` を見てください:
+=======
+alert( articles[0].title ); // CSS
+```
+
+Here `Article.compare` method 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.
+
+Let's say, we need multiple ways to create an article:
+
+1. Create by given parameters (`title`, `date` etc).
+2. Create an empty article with today's date.
+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.
+
+Such as `Article.createTodays()` here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Article {
@@ -87,7 +139,11 @@ class Article {
*!*
static createTodays() {
+<<<<<<< HEAD
// 思い出してください, this = Article
+=======
+ // remember, this = Article
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return new this("Today's digest", new Date());
}
*/!*
@@ -95,6 +151,7 @@ class Article {
let article = Article.createTodays();
+<<<<<<< HEAD
alert( article.title ); // Todays digest
```
@@ -113,26 +170,72 @@ Article.remove({ id: 12345 });
[recent browser=Chrome]
静的プロパティも可能で、通常のクラスプロパティと同じように見えますが、先頭に `static` が付きます。
+=======
+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.
+
+Static methods are also used in database-related classes to search/save/remove entries from the database, like this:
+
+```js
+// assuming Article is a special class for managing articles
+// static method to remove the article by id:
+Article.remove({id: 12345});
+```
+
+````warn header="Static methods aren't available for individual objects"
+Static methods are callable on classes, not on individual objects.
+
+E.g. such code won't work:
+
+```js
+// ...
+article.createTodays(); /// Error: article.createTodays is not a function
+```
+````
+
+## Static properties
+
+[recent browser=Chrome]
+
+Static properties are also possible, they look like regular class properties, but prepended by `static`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Article {
static publisher = "Ilya Kantor";
}
+<<<<<<< HEAD
alert(Article.publisher); // Ilya Kantor
```
これは直接 `Article` に代入するのと同じです。:
+=======
+alert( Article.publisher ); // Ilya Kantor
+```
+
+That is the same as a direct assignment to `Article`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
Article.publisher = "Ilya Kantor";
```
+<<<<<<< HEAD
## 静的プロパティとメソッドの継承 [#statics-and-inheritance]
静的プロパティとメソッドは継承されます。
例えば、以下のコードの `Animal.compare` と `Animal.planet` は継承され、`Rabbit.compare` と `Rabbit.planet` としてアクセス可能です。
+=======
+## Inheritance of static properties and methods [#statics-and-inheritance]
+
+Static properties and methods are inherited.
+
+For instance, `Animal.compare` and `Animal.planet` in the code below are inherited and accessible as `Rabbit.compare` and `Rabbit.planet`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {
@@ -177,6 +280,7 @@ rabbits[0].run(); // Black Rabbit runs with speed 5.
alert(Rabbit.planet); // Earth
```
+<<<<<<< HEAD
`Rabbit.compare` を呼び出すと、継承された `Animal.compare` が呼び出されます。
これはどのように機能しているでしょう?すでに推測したかもしれませんが、`extends` もまた `Rabbit` に `Animal` への参照を持つ `[[Prototype]]` を与えます。
@@ -191,11 +295,28 @@ alert(Rabbit.planet); // Earth
結果、継承は通常のものと静的なメソッド両方で機能します。
ここで、それを確認しましょう:
+=======
+Now when we 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`.
+
+
+
+So, `Rabbit extends Animal` creates two `[[Prototype]]` references:
+
+1. `Rabbit` function prototypally inherits from `Animal` function.
+2. `Rabbit.prototype` prototypally inherits from `Animal.prototype`.
+
+As a result, inheritance works both for regular and static methods.
+
+Here, let's check that by code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {}
class Rabbit extends Animal {}
+<<<<<<< HEAD
// 静的
alert(Rabbit.__proto__ === Animal); // true
@@ -214,6 +335,26 @@ alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
静的プロパティは、クラスレベルのデータを格納するときに使用され、インスタンスにバインドされません。
構文は次の通りです:
+=======
+// for statics
+alert(Rabbit.__proto__ === Animal); // true
+
+// for regular methods
+alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
+```
+
+## Summary
+
+Static methods are used for the functionality that belongs to the class "as a whole". It 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.
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class MyClass {
@@ -225,13 +366,23 @@ class MyClass {
}
```
+<<<<<<< HEAD
これは技術的には、クラス自身への代入と同じです:
+=======
+Technically, static declaration is the same as assigning to the class itself:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
MyClass.property = ...
MyClass.method = ...
```
+<<<<<<< HEAD
静的プロパティは継承されます。
`class B extends A` の場合、クラス `B` 自体のプロトタイプは `A` を指します、: `B.[[Prototype]] = A`。したがって、`B` の中にフィールドが見つからない場合は、検索は `A` の中で続行されます。
+=======
+Static properties and methods are inherited.
+
+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`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 0653aefa60..ceea564238 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
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# Private / protected プロパティとメソッド
オブジェクト指向プログラミングの最も重要な原則の 1 つは、内部インタフェースを外部インタフェースから切り離すことです。
@@ -88,6 +89,100 @@ coffeeMachine.waterAmount = 200;
これは言語レベルでは強制されていませんが、このようなプロパティやメソッドは外側からアクセスするべきではない、という慣習があります。ほとんどのプログラマはそれに従っています。
なので、プロパティは `_waterAmount` になります:
+=======
+
+# Private and protected properties and methods
+
+One of the most important principles of object oriented programming -- delimiting internal interface from the external one.
+
+That is "a must" practice in developing anything more complex than a "hello world" app.
+
+To understand this, let's break away from development and turn our eyes into the real world.
+
+Usually, devices that we're using are quite complex. But delimiting the internal interface from the external one allows to use them without problems.
+
+## A real-life example
+
+For instance, a coffee machine. Simple from outside: a button, a display, a few holes...And, surely, the result -- great coffee! :)
+
+
+
+But inside... (a picture from the repair manual)
+
+
+
+A lot of details. But we can use it without knowing anything.
+
+Coffee machines are quite reliable, aren't they? We can use one for years, and only if something goes wrong -- bring it for repairs.
+
+The secret of reliability and simplicity of a coffee machine -- all details are well-tuned and *hidden* inside.
+
+If we remove the protective cover from the coffee machine, then using it will be much more complex (where to press?), and dangerous (it can electrocute).
+
+As we'll see, in programming objects are like coffee machines.
+
+But in order to hide inner details, we'll use not a protective cover, but rather special syntax of the language and conventions.
+
+## Internal and external interface
+
+In object-oriented programming, properties and methods are split into two groups:
+
+- *Internal interface* -- methods and properties, accessible from other methods of the class, but not from the outside.
+- *External interface* -- methods and properties, accessible also from outside the class.
+
+If we continue the analogy with the coffee machine -- what's hidden inside: a boiler tube, heating element, and so on -- is its internal interface.
+
+An internal interface is used for the object to work, its details use each other. For instance, a boiler tube is attached to the heating element.
+
+But from the outside a coffee machine is closed by the protective cover, so that no one can reach those. Details are hidden and inaccessible. We can use its features via the external interface.
+
+So, all we need to use an object is to know its external interface. We may be completely unaware how it works inside, and that's great.
+
+That was a general introduction.
+
+In JavaScript, there are two types of object fields (properties and methods):
+
+- Public: accessible from anywhere. They comprise the external interface. Until 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 (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.
+
+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"
+
+Let's make a simple coffee machine class first:
+
+```js run
+class CoffeeMachine {
+ waterAmount = 0; // the amount of water inside
+
+ constructor(power) {
+ this.power = power;
+ alert( `Created a coffee-machine, power: ${power}` );
+ }
+
+}
+
+// create the coffee machine
+let coffeeMachine = new CoffeeMachine(100);
+
+// add water
+coffeeMachine.waterAmount = 200;
+```
+
+Right now the properties `waterAmount` and `power` are public. We can easily get/set them from the outside to any value.
+
+Let's change `waterAmount` property to protected to have more control over it. For instance, we don't want anyone to set it below zero.
+
+**Protected properties are usually prefixed with an underscore `_`.**
+
+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`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class CoffeeMachine {
@@ -107,6 +202,7 @@ class CoffeeMachine {
constructor(power) {
this._power = power;
}
+<<<<<<< HEAD
}
// コーヒーメーカーを生成
@@ -125,6 +221,27 @@ coffeeMachine.waterAmount = -10; // _waterAmount は -10 ではなく、 0 に
これはまさにコーヒーメーカーの電力(power)のケースです。この値は決して変わりません。
そうするためには、getter のみを作成する必要があります。setter は不要です。:
+=======
+
+}
+
+// create the coffee machine
+let coffeeMachine = new CoffeeMachine(100);
+
+// add water
+coffeeMachine.waterAmount = -10; // _waterAmount will become 0, not -10
+```
+
+Now the access is under control, so setting the water amount below zero becomes impossible.
+
+## Read-only "power"
+
+For `power` property, let's make it read-only. It sometimes happens that a property must be set at creation time only, and then never modified.
+
+That's exactly the case for a coffee machine: power never changes.
+
+To do so, we only need to make getter, but not the setter:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class CoffeeMachine {
@@ -137,13 +254,21 @@ class CoffeeMachine {
get power() {
return this._power;
}
+<<<<<<< HEAD
}
// コーヒーメーカーを作成
+=======
+
+}
+
+// create the coffee machine
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let coffeeMachine = new CoffeeMachine(100);
alert(`Power is: ${coffeeMachine.power}W`); // Power is: 100W
+<<<<<<< HEAD
coffeeMachine.power = 25; // Error (setter はないので)
```
@@ -151,24 +276,42 @@ coffeeMachine.power = 25; // Error (setter はないので)
ここでは、getter/setter 構文を使いました。
しかし、多くの場合は次のような `get.../set...` 関数が好まれます。:
+=======
+coffeeMachine.power = 25; // Error (no setter)
+```
+
+````smart header="Getter/setter functions"
+Here we used getter/setter syntax.
+
+But most of the time `get.../set...` functions are preferred, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class CoffeeMachine {
_waterAmount = 0;
*!*setWaterAmount(value)*/!* {
+<<<<<<< HEAD
if (value < 0) throw new Error("Negative water");
+=======
+ if (value < 0) value = 0;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this._waterAmount = value;
}
*!*getWaterAmount()*/!* {
+<<<<<<< HEAD
return this.waterAmount;
+=======
+ return this._waterAmount;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
new CoffeeMachine().setWaterAmount(100);
```
+<<<<<<< HEAD
これは少し長く見えますが、関数はより柔軟です。たとえ現時点では必要ないとしても、この方法の場合、複数の引数を受け取ることができます。そのため、将来なにかをリファクタする必要がある場合に備えるなら、関数はより安全な選択肢です。
もちろん、これはトレードオフです。一方で get/set 構文はより短くかけます。ここに厳密なルールはないので、決めるのはあなた次第です。
@@ -178,17 +321,36 @@ new CoffeeMachine().setWaterAmount(100);
`class MegaMachine extends CoffeeMachine` と継承した場合、新しいクラスのメソッドから `this._waterAmount` や `this._power` にアクセスするのを妨げるものは何もありません。
つまり、protected フィールは当然のことながら継承可能です。下で見ていく private なものとは異なります。
+=======
+That looks a bit longer, but functions are more flexible. They can accept multiple arguments (even if we don't need them right now).
+
+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"
+If we inherit `class MegaMachine extends CoffeeMachine`, then nothing prevents us from accessing `this._waterAmount` or `this._power` from the methods of the new class.
+
+So protected fields are naturally inheritable. Unlike private ones that we'll see below.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
## Private "#waterLimit"
[recent browser=none]
+<<<<<<< HEAD
プライベートなプロパティやメソッドに対する言語レベルのサポートを提供する、ほぼ標準的な完成した JavaScript の提案があります。
プライベートは `#` から始める必要があります。それらはクラス内部からのみアクセス可能です。
例えば、ここではプライベートな `#waterLimit` プロパティを追加し、水量をチェックするロジックを別のメソッドに抜き出しています:
+=======
+There's a finished JavaScript proposal, almost in the standard, that provides language-level support for private properties and methods.
+
+Privates should start with `#`. They are only accessible from inside the class.
+
+For instance, here's a private `#waterLimit` property and the water-checking private method `#fixWaterAmount`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class CoffeeMachine {
@@ -218,6 +380,7 @@ coffeeMachine.#waterLimit = 1000; // Error
*/!*
```
+<<<<<<< HEAD
言語レベルで、`#` はフィールドがプライベートであることを示す特別な記号です。その外側や継承したクラスからアクセスすることはできません。
プライベートフィールドはパブリックなものと衝突しません。プライベートな `#waterAmount` とパブリックな `waterAmount` フィールド両方を同時にもつことができます。
@@ -226,6 +389,17 @@ coffeeMachine.#waterLimit = 1000; // Error
```js run
class CoffeeMachine {
+=======
+On the language level, `#` is a special sign that the field is private. We can't access it from outside or from inheriting classes.
+
+Private fields do not conflict with public ones. We can have both private `#waterAmount` and public `waterAmount` fields at the same time.
+
+For instance, let's make `waterAmount` an accessor for `#waterAmount`:
+
+```js run
+class CoffeeMachine {
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
#waterAmount = 0;
get waterAmount() {
@@ -244,6 +418,7 @@ machine.waterAmount = 100;
alert(machine.#waterAmount); // Error
```
+<<<<<<< HEAD
protected なものとは異なり、private フィールドは言語レベルで強制されます。
なお、`CoffeeMachine` を継承した場合、`#waterAmount` へアクセスはできません。アクセスするには、`waterAmount` の getter/setter を経由する必要があります。:
@@ -253,28 +428,53 @@ class CoffeeMachine extends CoffeeMachine() {
method() {
*!*
alert( this.#waterAmount ); // Error: CoffeeMachine からのみアクセス可能
+=======
+Unlike protected ones, private fields are enforced by the language itself. That's a good thing.
+
+But if we inherit from `CoffeeMachine`, then we'll have no direct access to `#waterAmount`. We'll need to rely on `waterAmount` getter/setter:
+
+```js
+class MegaCoffeeMachine extends CoffeeMachine {
+ method() {
+*!*
+ alert( this.#waterAmount ); // Error: can only access from CoffeeMachine
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
}
```
+<<<<<<< HEAD
多くのシナリオにおいて、このような制限は厳しすぎます。`CoffeeMachine` を拡張する際には、その内部にアクセスすべき正当な理由があるかもしれません。そのため、protected フィールドは言語レベルの構文ではサポートされていませんが、多くの場合 protected フィールドが使われています。
````warn
Private フィールドは特別です。
通常だと this[name] でフィールドにアクセスできます。:
+=======
+In many scenarios such limitation is too severe. If we extend a `CoffeeMachine`, we may have legitimate reasons to access its internals. That's why protected fields are used more often, even though they are not supported by the language syntax.
+
+````warn header="Private fields are not available as this[name]"
+Private fields are special.
+
+As we know, usually we can access fields using `this[name]`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class User {
...
sayHi() {
let fieldName = "name";
+<<<<<<< HEAD
alert(`Hello, ${this[fieldName]}`);
+=======
+ alert(`Hello, ${*!*this[fieldName]*/!*}`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
しかし、private フィールドだとそれはできません。: `this['#name']` は期待通り動作しません。これは private であることを維持するための、構文上の制限になります。
````
@@ -315,3 +515,45 @@ Supportable
- private フィールドは `#` で始まります。JavaScript では、クラス内からのみアクセスできます。
現時点では、private フィールドはブラウザ間では十分にはサポートされていませんが、polyfill することができます。
+=======
+With private fields that's impossible: `this['#name']` doesn't work. That's a syntax limitation to ensure privacy.
+````
+
+## Summary
+
+In terms of OOP, delimiting of the internal interface from the external one is called [encapsulation](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)).
+
+It gives the following benefits:
+
+Protection for users, so that they don't shoot themselves in the foot
+: Imagine, there's a team of developers using a coffee machine. It was made by the "Best CoffeeMachine" company, and works fine, but a protective cover was removed. So the internal interface is exposed.
+
+ All developers are civilized -- they use the coffee machine as intended. But one of them, John, decided that he's the smartest one, and made some tweaks in the coffee machine internals. So the coffee machine failed two days later.
+
+ That's surely not John's fault, but rather the person who removed the protective cover and let John do his manipulations.
+
+ The same in programming. If a user of a class will change things not intended to be changed from the outside -- the consequences are unpredictable.
+
+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 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 internally, but still simple to upgrade if the external interface is the same.
+
+Hiding complexity
+: People adore using things that are simple. At least from outside. What's inside is a different thing.
+
+ Programmers are not an exception.
+
+ **It's always convenient when implementation details are hidden, and a simple, well-documented external interface is available.**
+
+To hide an internal interface we use either protected or private properties:
+
+- Protected fields start with `_`. That's a well-known convention, not enforced at the language level. Programmers should only access a field starting with `_` from its class and classes inheriting from it.
+- Private fields start with `#`. JavaScript makes sure we can only access those from inside the class.
+
+Right now, private fields are not well-supported among browsers, but can be polyfilled.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/05-extend-natives/article.md b/1-js/09-classes/05-extend-natives/article.md
index 8eaafdff5c..48f8b6de6a 100644
--- a/1-js/09-classes/05-extend-natives/article.md
+++ b/1-js/09-classes/05-extend-natives/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# 組み込みのクラスを拡張する
Array、Map などの組み込みのクラスも拡張可能です。
@@ -6,6 +7,17 @@ Array、Map などの組み込みのクラスも拡張可能です。
```js run
// 1つメソッドを追加しています(その他のことももちろん可能です)
+=======
+
+# Extending built-in classes
+
+Built-in classes like Array, Map and others are extendable also.
+
+For instance, here `PowerArray` inherits from the native `Array`:
+
+```js run
+// add one more method to it (can do more)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
class PowerArray extends Array {
isEmpty() {
return this.length === 0;
@@ -15,11 +27,16 @@ class PowerArray extends Array {
let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false
+<<<<<<< HEAD
let filteredArr = arr.filter((item) => item >= 10);
+=======
+let filteredArr = arr.filter(item => item >= 10);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(filteredArr); // 10, 50
alert(filteredArr.isEmpty()); // false
```
+<<<<<<< HEAD
とても興味深い点に注目してください。`filter` や `map` といった組み込みのメソッドは、継承された型 `PowerArray` と同じ型の新しいオブジェクトを返します。そのために、内部の実装はオブジェクトの `constructor` プロパティを使用します。
上の例では、
@@ -35,6 +52,22 @@ arr.constructor === PowerArray;
特別な静的な getter `Symbol.species` を追加することができます。これが存在する場合、`map` や `filter` などの場合に Javascript が内部的に使用するコンストラクタを返す必要があります。
もし、`map` や `filter` のような組み込みのメソッドが通常の配列を返してほしい場合、次のように `Symbol.species` で `Array` を返すようにします:
+=======
+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 the object's `constructor` property for that.
+
+In the example above,
+```js
+arr.constructor === PowerArray
+```
+
+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 it 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` or `filter` to return regular arrays, we can return `Array` in `Symbol.species`, like here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class PowerArray extends Array {
@@ -43,7 +76,11 @@ class PowerArray extends Array {
}
*!*
+<<<<<<< HEAD
// 組み込みのメソッドは、これをコンストラクタとして使います
+=======
+ // built-in methods will use this as the constructor
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
static get [Symbol.species]() {
return Array;
}
@@ -53,15 +90,24 @@ class PowerArray extends Array {
let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false
+<<<<<<< HEAD
// filter はコンストラクタとして arr.constructor[Symbol.species] を使って新しい配列を作ります
let filteredArr = arr.filter(item => item >= 10);
*!*
// filteredArr は PowerArray ではなく Array です
+=======
+// filter creates new array using arr.constructor[Symbol.species] as constructor
+let filteredArr = arr.filter(item => item >= 10);
+
+*!*
+// filteredArr is not PowerArray, but Array
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
```
+<<<<<<< HEAD
ご覧の通り、これで `.filter` は `Array` を返します。そのため、拡張機能はこれ以上渡されません。
```smart header="他のコレクションも同様に動作します"
@@ -87,3 +133,30 @@ alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
`Date` と `Object` の間に繋がりはないことに注目してください。`Object` と `Date` は両方とも独立し、`Date.prototype` は `Object.prototype` を継承しているだけです。
これは組み込みのオブジェクトの継承と `extends` をして得られるものとの比較における重要な違いです。
+=======
+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. That was thoroughly explained in the article [](info:static-properties-methods#statics-and-inheritance).
+
+But built-in classes are an exception. They don't inherit statics 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 reference `Object`, so there's no, for instance, `Array.keys()` (or `Date.keys()`) static method.
+
+Here's the picture structure for `Date` and `Object`:
+
+
+
+As you can see, there's no link between `Date` and `Object`. They are independent, only `Date.prototype` inherits from `Object.prototype`.
+
+That's an important difference of inheritance between built-in objects compared to what we get with `extends`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/06-instanceof/1-strange-instanceof/solution.md b/1-js/09-classes/06-instanceof/1-strange-instanceof/solution.md
index c48a583004..e2bfed1bf5 100644
--- a/1-js/09-classes/06-instanceof/1-strange-instanceof/solution.md
+++ b/1-js/09-classes/06-instanceof/1-strange-instanceof/solution.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
はい、確かに奇妙に見えます。
しかし、`instanceof` は関数を気にするのではなく、プロトタイプチェーンに対してマッチする `prototype` について気にします。
@@ -5,3 +6,12 @@
そして、ここでは `a.__proto__ == B.prototype` なので、`instanceof` が `true` を返します。
従って、`instanceof` のロジックに基づいて、`prototype` は実際にはコンストラクタ関数ではなく型を定義します。
+=======
+Yeah, looks strange indeed.
+
+But `instanceof` does not care about the function, but rather about its `prototype`, that it matches against the prototype chain.
+
+And here `a.__proto__ == B.prototype`, so `instanceof` returns `true`.
+
+So, by the logic of `instanceof`, the `prototype` actually defines the type, not the constructor function.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/06-instanceof/1-strange-instanceof/task.md b/1-js/09-classes/06-instanceof/1-strange-instanceof/task.md
index acaf54d0fd..b51001088a 100644
--- a/1-js/09-classes/06-instanceof/1-strange-instanceof/task.md
+++ b/1-js/09-classes/06-instanceof/1-strange-instanceof/task.md
@@ -2,9 +2,15 @@ importance: 5
---
+<<<<<<< HEAD
# 奇妙な instanceof
なぜ下の `instanceof` は `true` を返すのでしょう? `a` が `B()` によって作られたものでないことは簡単に分かります。
+=======
+# Strange instanceof
+
+In the code below, why does `instanceof` return `true`? We can easily see that `a` is not created by `B()`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function A() {}
diff --git a/1-js/09-classes/06-instanceof/article.md b/1-js/09-classes/06-instanceof/article.md
index 8c4768bb62..cdd82566f3 100644
--- a/1-js/09-classes/06-instanceof/article.md
+++ b/1-js/09-classes/06-instanceof/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# クラスのチェック: "instanceof"
`instanceof` 演算子でオブジェクトが特定のクラスに属しているのかを確認することができます。また、継承も考慮されます。
@@ -7,36 +8,69 @@
## instanceof 演算子 [#ref-instanceof]
構文は次の通りです:
+=======
+# Class checking: "instanceof"
+
+The `instanceof` operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
+
+Such a check may be necessary in many cases. For example, it can be used for building a *polymorphic* function, the one that treats arguments differently depending on their type.
+
+## The instanceof operator [#ref-instanceof]
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
obj instanceof Class
```
+<<<<<<< HEAD
それは `obj` が `Class` (または、それを継承しているクラス)に属している場合に `true` を返します。
例:
+=======
+It returns `true` if `obj` belongs to the `Class` or a class inheriting from it.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Rabbit {}
let rabbit = new Rabbit();
+<<<<<<< HEAD
// Rabbit クラスのオブジェクト?
+=======
+// is it an object of Rabbit class?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
alert( rabbit instanceof Rabbit ); // true
*/!*
```
+<<<<<<< HEAD
コンストラクタ関数でも動作します。:
```js run
*!*
// class の代わり
+=======
+It also works with constructor functions:
+
+```js run
+*!*
+// instead of class
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
function Rabbit() {}
*/!*
alert( new Rabbit() instanceof Rabbit ); // true
```
+<<<<<<< HEAD
...また `Array` のような組み込みクラスでも動作します。:
+=======
+...And with built-in classes like `Array`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let arr = [1, 2, 3];
@@ -44,6 +78,7 @@ alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true
```
+<<<<<<< HEAD
`arr` は `Object` クラスにも属していることに留意してください。`Array` はプロトタイプ的に `Object` を継承しているためです。
通常、`instanceof` 演算子はチェックのためにプロトタイプチェーンを検査します。この動きに対して、静的メソッド `Symbol.hasInstance` でカスタムロジックが設定できます。
@@ -57,6 +92,21 @@ alert( arr instanceof Object ); // true
```js run
// catEat プロパティをもつものは animal と想定する
// instanceOf チェックを設定
+=======
+Please note that `arr` also belongs to the `Object` class. That's because `Array` prototypically inherits from `Object`.
+
+Normally, `instanceof` 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`, 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 with canEat property is an animal
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
class Animal {
static [Symbol.hasInstance](obj) {
if (obj.canEat) return true;
@@ -65,6 +115,7 @@ alert( arr instanceof Object ); // true
let obj = { canEat: true };
+<<<<<<< HEAD
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj)が呼ばれます
```
@@ -83,6 +134,26 @@ alert( arr instanceof Object ); // true
上の例では、``rabbit.__proto__ === Rabbit.prototype` なので、すぐに回答が得られます。
継承のケースでは、2つめのステップでマッチします:
+=======
+ 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 Class` checks whether `Class.prototype` is equal to one of the prototypes in the `obj` prototype chain.
+
+ In other words, compare one after another:
+ ```js
+ 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.__proto__ === Rabbit.prototype`, so that gives the answer immediately.
+
+ In the case of an inheritance, the match will be at the second step:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Animal {}
@@ -93,12 +164,17 @@ alert( arr instanceof Object ); // true
alert(rabbit instanceof Animal); // true
*/!*
+<<<<<<< HEAD
// rabbit.__proto__ == Rabbit.prototype
+=======
+ // rabbit.__proto__ === Animal.prototype (no match)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
// rabbit.__proto__.__proto__ === Animal.prototype (match!)
*/!*
```
+<<<<<<< HEAD
これは、`rabbit instanceof Animal` と `Animal.prototype` を比較したものです。:

@@ -110,28 +186,55 @@ alert( arr instanceof Object ); // true
これは `prototype` が変更されたときに興味深い結果につながります。
このように:
+=======
+Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
+
+
+
+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)`.
+
+It'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 a `prototype` property is changed after the object is created.
+
+Like here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function Rabbit() {}
let rabbit = new Rabbit();
+<<<<<<< HEAD
// prototype を変更します
Rabbit.prototype = {};
// ...もう rabbit ではありません
+=======
+// changed the prototype
+Rabbit.prototype = {};
+
+// ...not a rabbit any more!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
alert( rabbit instanceof Rabbit ); // false
*/!*
```
+<<<<<<< HEAD
## おまけ: 型のための Object toString
私たちは通常の文字列は `[object Object]` という文字列に変換されることをすでに知っています。:
+=======
+## Bonus: Object.prototype.toString for the type
+
+We already know that plain objects are converted to string as `[object Object]`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let obj = {};
alert(obj); // [object Object]
+<<<<<<< HEAD
alert(obj.toString()); // 同じ
```
@@ -163,6 +266,39 @@ alert( objectToString.call(arr) ); // [object Array]
ここでは、コンテキスト `this=arr` で関数 `objectToString` を実行するため、[デコレータと転送, call/apply](info:call-apply-decorators) の章で説明した [call](mdn:js/function/call) を使いました。
内部的には、`toString` アルゴリズムは `this` を検査し、対応する結果を返します。ほかの例です。:
+=======
+alert(obj.toString()); // the same
+```
+
+That's their implementation of `toString`. But there's a hidden feature that makes `toString` actually much more powerful than that. We can use it as an extended `typeof` and an alternative for `instanceof`.
+
+Sounds strange? Indeed. Let's demystify.
+
+By [specification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), the built-in `toString` can be extracted from the object and executed in the context of any other value. And its result depends on that value.
+
+- For a number, it will be `[object Number]`
+- For a boolean, it will be `[object Boolean]`
+- For `null`: `[object Null]`
+- For `undefined`: `[object Undefined]`
+- For arrays: `[object Array]`
+- ...etc (customizable).
+
+Let's demonstrate:
+
+```js run
+// copy toString method into a variable for convenience
+let objectToString = Object.prototype.toString;
+
+// what type is this?
+let arr = [];
+
+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`.
+
+Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let s = Object.prototype.toString;
@@ -174,6 +310,7 @@ alert( s.call(alert) ); // [object Function]
### Symbol.toStringTag
+<<<<<<< HEAD
Object `toString` の振る舞いは特別なオブジェクトプロパティ `Symbol.toStringTag` を使用してカスタマイズできます。
例:
@@ -181,22 +318,40 @@ Object `toString` の振る舞いは特別なオブジェクトプロパティ `
```js run
let user = {
[Symbol.toStringTag]: 'User'
+=======
+The behavior of Object `toString` can be customized using a special object property `Symbol.toStringTag`.
+
+For instance:
+
+```js run
+let user = {
+ [Symbol.toStringTag]: "User"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
};
alert( {}.toString.call(user) ); // [object User]
```
+<<<<<<< HEAD
ほとんどの環境固有のオブジェクトには、このようなプロパティがあります。これはいくつかのブラウザ固有の例です。:
```js run
// 環境固有のオブジェクトとクラスのtoStringTag:
alert( window[Symbol.toStringTag]); // window
+=======
+For most environment-specific objects, there is such a property. Here are some browser specific examples:
+
+```js run
+// toStringTag for the environment-specific object and class:
+alert( window[Symbol.toStringTag]); // Window
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( XMLHttpRequest.prototype[Symbol.toStringTag] ); // XMLHttpRequest
alert( {}.toString.call(window) ); // [object Window]
alert( {}.toString.call(new XMLHttpRequest()) ); // [object XMLHttpRequest]
```
+<<<<<<< HEAD
ご覧の通り、結果は正確に `Symbol.toStringTag` (存在する場合)で、`[object ...]` の中にラップされています。
最終的には、プリミティブなデータ型だけでなく、組み込みオブジェクトのためにも機能し、カスタマイズすることもできる "強化された typeof" があります。
@@ -216,3 +371,24 @@ alert( {}.toString.call(new XMLHttpRequest()) ); // [object XMLHttpRequest]
ご覧のように、`{}.toString` は技術的には "より高度な" `typeof` です。
そして、`instanceof` 演算子は、クラス階層を扱っていて継承を考慮したクラスのチェックをしたい場合に本当に輝きます。
+=======
+As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped into `[object ...]`.
+
+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.
+
+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 summarize the type-checking methods that we know:
+
+| | works for | returns |
+|---------------|-------------|---------------|
+| `typeof` | primitives | string |
+| `{}.toString` | primitives, built-in objects, objects with `Symbol.toStringTag` | string |
+| `instanceof` | objects | true/false |
+
+As we can see, `{}.toString` is technically a "more advanced" `typeof`.
+
+And `instanceof` operator really shines when we are working with a class hierarchy and want to check for the class taking into account inheritance.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/07-mixins/article.md b/1-js/09-classes/07-mixins/article.md
index 8709ab8399..fd9aab1e78 100644
--- a/1-js/09-classes/07-mixins/article.md
+++ b/1-js/09-classes/07-mixins/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# ミックスイン
JavaScriptでは、単一のオブジェクトからのみ継承できます。オブジェクトの `[[Prototype]]` は1つしかありません。そしてクラスは単一の他のクラスだけを拡張することができます。
@@ -17,6 +18,27 @@ Wikipedis の定義によると、[mixin](https://en.wikipedia.org/wiki/Mixin)
JavaScriptで mixin を作る最もシンプルな方法は、役立つメソッドをもつオブジェクトを作ることです。そうすることで、それらを簡単にどのクラスのプロトタイプにもマージできます。
例えば、ここでは mixin `sayHiMixin` は `User` のためのいくつかの "スピーチ" を追加するために使われます。:
+=======
+# Mixins
+
+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, we have a class `StreetSweeper` and a class `Bicycle`, and want to make their mix: a `StreetSweepingBicycle`.
+
+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 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 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`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
@@ -24,15 +46,26 @@ JavaScriptで mixin を作る最もシンプルな方法は、役立つメソッ
*/!*
let sayHiMixin = {
sayHi() {
+<<<<<<< HEAD
alert("Hello " + this.name);
},
sayBye() {
alert("Bye " + this.name);
+=======
+ alert(`Hello ${this.name}`);
+ },
+ sayBye() {
+ alert(`Bye ${this.name}`);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
*!*
+<<<<<<< HEAD
// 使い方:
+=======
+// usage:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
class User {
constructor(name) {
@@ -40,6 +73,7 @@ class User {
}
}
+<<<<<<< HEAD
// メソッドをコピー
Object.assign(User.prototype, sayHiMixin);
@@ -48,6 +82,16 @@ new User("Dude").sayHi(); // Hi Dude!
```
これは継承ではなく、単純なメソッドのコピーです。従って、`User` は他のクラスを拡張することができ、さらに以下のように追加のメソッドをミックスインするとして含めることができます:
+=======
+// copy the methods
+Object.assign(User.prototype, sayHiMixin);
+
+// now User can say hi
+new User("Dude").sayHi(); // Hello Dude!
+```
+
+There's no inheritance, but a simple method copying. So `User` may inherit from another class and also include the mixin to "mix-in" the additional methods, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
class User extends Person {
@@ -57,9 +101,15 @@ class User extends Person {
Object.assign(User.prototype, sayHiMixin);
```
+<<<<<<< HEAD
ミックスインは自身の内部で継承を活用することもできます。
例えば、ここでは `sayHiMixin` は `sayMixin` を継承しています。:
+=======
+Mixins can make use of inheritance inside themselves.
+
+For instance, here `sayHiMixin` inherits from `sayMixin`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let sayMixin = {
@@ -69,6 +119,7 @@ let sayMixin = {
};
let sayHiMixin = {
+<<<<<<< HEAD
__proto__: sayMixin, // (またはここで prototype を設定するのに Object.create が使えます)
sayHi() {
@@ -79,6 +130,18 @@ let sayHiMixin = {
},
sayBye() {
super.say("Bye " + this.name); // (*)
+=======
+ __proto__: sayMixin, // (or we could use Object.setPrototypeOf to set the prototype here)
+
+ sayHi() {
+ *!*
+ // call parent method
+ */!*
+ super.say(`Hello ${this.name}`); // (*)
+ },
+ sayBye() {
+ super.say(`Bye ${this.name}`); // (*)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
};
@@ -88,6 +151,7 @@ class User {
}
}
+<<<<<<< HEAD
// メソッドをコピー
Object.assign(User.prototype, sayHiMixin);
@@ -120,11 +184,49 @@ new User("Dude").sayHi(); // Hello Dude!
あるいは、`menu` はメニュー項目が選択されたときにイベント `"select"` を生成でき、他のオブジェクトはそのイベントに反応するためにハンドラを割り当てることができます。
これはそのコードです:
+=======
+// copy the methods
+Object.assign(User.prototype, sayHiMixin);
+
+// now User can say hi
+new User("Dude").sayHi(); // Hello Dude!
+```
+
+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.
+
+Here's the diagram (see the right part):
+
+
+
+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 in the picture above.
+
+As `super` looks for parent methods in `[[HomeObject]].[[Prototype]]`, that means it searches `sayHiMixin.[[Prototype]]`.
+
+## EventMixin
+
+Now let's make a mixin for real life.
+
+An important feature of many browser objects (for instance) is that they can generate events. Events are a great way to "broadcast information" to anyone who wants it. So let's make a mixin that allows us 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 the `.trigger` call.
+- ...And the method `.off(name, handler)` that removes the `handler` listener.
+
+After adding the mixin, an object `user` will be able to generate an event `"login"` when the visitor logs in. And another object, say, `calendar` may want to listen for such events to load the calendar for the logged-in person.
+
+Or, a `menu` can generate the event `"select"` when a menu item is selected, and other objects may assign handlers to react on that event. And so on.
+
+Here's the code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let eventMixin = {
/**
+<<<<<<< HEAD
* イベントの購読, 使い方:
+=======
+ * Subscribe to event, usage:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
* menu.on('select', function(item) { ... }
*/
on(eventName, handler) {
@@ -136,6 +238,7 @@ let eventMixin = {
},
/**
+<<<<<<< HEAD
* 購読のキャンセル 使い方:
* menu.off('select', handler)
*/
@@ -144,12 +247,23 @@ let eventMixin = {
if (!handlers) return;
for(let i = 0; i < handlers.length; i++) {
if (handlers[i] == handler) {
+=======
+ * Cancel the subscription, usage:
+ * menu.off('select', handler)
+ */
+ off(eventName, handler) {
+ let handlers = this._eventHandlers?.[eventName];
+ if (!handlers) return;
+ for (let i = 0; i < handlers.length; i++) {
+ if (handlers[i] === handler) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
handlers.splice(i--, 1);
}
}
},
/**
+<<<<<<< HEAD
* イベントを生成してデータをアタッチ
* this.trigger('select', data1, data2);
*/
@@ -159,12 +273,24 @@ let eventMixin = {
}
// ハンドラ呼び出し
+=======
+ * Generate an event with the given name and data
+ * this.trigger('select', data1, data2);
+ */
+ trigger(eventName, ...args) {
+ if (!this._eventHandlers?.[eventName]) {
+ return; // no handlers for that event name
+ }
+
+ // call the handlers
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
this._eventHandlers[eventName].forEach(handler => handler.apply(this, args));
}
};
```
+<<<<<<< HEAD
1. `.on(eventName, handler)` -- その名前のイベントが発生した時に実行するための関数 `handler` を割り当てます。ハンドラは `_eventHandlers` プロパティの中に格納されます。
2. `.off(eventName, handler)` -- ハンドラリストから関数を削除します。
3. `.trigger(eventName, ...args)` -- イベントを生成します: すべての割り当てられたハンドラが呼び出され、`args` がそれらの引数として渡されます。
@@ -173,16 +299,31 @@ let eventMixin = {
```js run
// クラスを作成
+=======
+- `.on(eventName, handler)` -- assigns function `handler` to run when the event with that name occurs. Technically, there's an `_eventHandlers` property that stores an array of handlers for each event name, and it just adds it to the list.
+- `.off(eventName, handler)` -- removes the function from the handlers list.
+- `.trigger(eventName, ...args)` -- generates the event: all handlers from `_eventHandlers[eventName]` are called, with a list of arguments `...args`.
+
+Usage:
+
+```js run
+// Make a class
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
class Menu {
choose(value) {
this.trigger("select", value);
}
}
+<<<<<<< HEAD
// mixin を追加
+=======
+// Add the mixin with event-related methods
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
Object.assign(Menu.prototype, eventMixin);
let menu = new Menu();
+<<<<<<< HEAD
// 選択時にハンドラを呼び出し
*!*
menu.on("select", value => alert("Value selected: " + value));
@@ -206,3 +347,28 @@ menu.choose("123"); // 選択された値
上で見てきたイベントハンドリングのように、複数の振る舞いを追加することでクラスを拡張する方法としてミックスインが利用できます。
ミックスインで誤って既存のクラスメソッドを上書きすると、競合が発生する可能性があります。そのため、一般的には、このような可能性を最小化するためにも、ミックスインの命名についてよく考える必要があります。
+=======
+// add a handler, to be called on selection:
+*!*
+menu.on("select", value => alert(`Value selected: ${value}`));
+*/!*
+
+// triggers the event => the handler above runs and shows:
+// Value selected: 123
+menu.choose("123");
+```
+
+Now, if we'd like any code to react to a menu selection, we can listen for it with `menu.on(...)`.
+
+And `eventMixin` mixin makes it easy to add such behavior to as many classes as we'd like, without interfering with the inheritance chain.
+
+## Summary
+
+*Mixin* -- is a generic object-oriented programming term: a class that contains methods for other classes.
+
+Some other languages 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 adding multiple behaviors, like event-handling as we have seen above.
+
+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 happening.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/09-classes/07-mixins/head.html b/1-js/09-classes/07-mixins/head.html
index 77ea38b204..20e3a63547 100644
--- a/1-js/09-classes/07-mixins/head.html
+++ b/1-js/09-classes/07-mixins/head.html
@@ -18,7 +18,7 @@
* menu.off('select', handler)
*/
off(eventName, handler) {
- let handlers = this._eventHandlers && this._eventHandlers[eventName];
+ let handlers = this._eventHandlers?.[eventName];
if (!handlers) return;
for(let i = 0; i < handlers.length; i++) {
if (handlers[i] == handler) {
diff --git a/1-js/09-classes/index.md b/1-js/09-classes/index.md
index dfe284a989..4d7fa709b0 100644
--- a/1-js/09-classes/index.md
+++ b/1-js/09-classes/index.md
@@ -1 +1,5 @@
+<<<<<<< HEAD
# クラス
+=======
+# Classes
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 f243b59687..a340516d95 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
@@ -1,8 +1,16 @@
+<<<<<<< HEAD
その違いは、関数内のコードを見ると明らかになります。
もし `try..catch` の "飛び出し" がある場合、振る舞いは異なります。
例えば、`try..catch` の中で `return` がある場合です。`finally` 句は `try..catch` が *どのような終わり方の場合にでも* 動作します。たとえ、`return` 文経由でさえも。
+=======
+The difference becomes obvious when we look at the code inside a function.
+
+The behavior is different if there's a "jump out" of `try...catch`.
+
+For instance, when there's a `return` inside `try...catch`. The `finally` clause works in case of *any* exit from `try...catch`, even via the `return` statement: right after `try...catch` is done, but before the calling code gets the control.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function f() {
@@ -11,7 +19,11 @@ function f() {
*!*
return "result";
*/!*
+<<<<<<< HEAD
} catch (e) {
+=======
+ } catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
/// ...
} finally {
alert('cleanup!');
@@ -21,18 +33,30 @@ function f() {
f(); // cleanup!
```
+<<<<<<< HEAD
...もしくは次のように `throw` がある場合:
+=======
+...Or when there's a `throw`, like here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function f() {
try {
alert('start');
throw new Error("an error");
+<<<<<<< HEAD
} catch (e) {
// ...
if("can't handle the error") {
*!*
throw e;
+=======
+ } catch (err) {
+ // ...
+ if("can't handle the error") {
+*!*
+ throw err;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
@@ -44,4 +68,8 @@ function f() {
f(); // cleanup!
```
+<<<<<<< HEAD
ここで `finally` はクリーンアップを保証します。もし `f` の終わりにコードをおいた場合は実行されない場合があります。
+=======
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/task.md b/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/task.md
index 57b3803373..236af9a88e 100644
--- a/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/task.md
+++ b/1-js/10-error-handling/1-try-catch/1-finally-or-code-after/task.md
@@ -4,13 +4,20 @@ importance: 5
# Finally or just the code?
+<<<<<<< HEAD
2つのコードの断片を比較してみてください。
1. 1つ目は `try..catch` のあとにコードを実行するために `finally` を使います:
+=======
+Compare the two code fragments.
+
+1. The first one uses `finally` to execute the code after `try...catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
work work
+<<<<<<< HEAD
} catch (e) {
handle errors
} finally {
@@ -20,15 +27,31 @@ importance: 5
}
```
2. 2つ目は `try..catch` の直後にクリーンアップする処理を置きます:
+=======
+ } catch (err) {
+ handle errors
+ } finally {
+ *!*
+ cleanup the working space
+ */!*
+ }
+ ```
+2. The second fragment puts the cleaning right after `try...catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
work work
+<<<<<<< HEAD
} catch (e) {
+=======
+ } catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
handle errors
}
*!*
+<<<<<<< HEAD
作業場所のクリーンアップ
*/!*
```
@@ -36,3 +59,12 @@ importance: 5
私たちは、処理が開始された後には、それがエラーかどうかは関係なく必ずクリーンアップが必要です。
`finally` を使うことの利点はあるでしょうか?それとも両方のコードは同じでしょうか?もし利点がある場合はそれが関係する例を挙げてください。
+=======
+ cleanup the working space
+ */!*
+ ```
+
+We definitely need the cleanup after the work, doesn't matter if there was an error or not.
+
+Is there an advantage here in using `finally` or both code fragments are equal? If there is such an advantage, then give an example when it matters.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
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 417961962a..eb4cbd14da 100644
--- a/1-js/10-error-handling/1-try-catch/article.md
+++ b/1-js/10-error-handling/1-try-catch/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# エラーハンドリング, "try..catch"
どんなに我々のプログラミングが素晴らしくても、スクリプトがエラーになることはあります。それはミス、予期しないユーザ入力、間違ったサーバレスポンスやその他多くの理由により発生する可能性があります。
@@ -9,6 +10,19 @@
## "try..catch" 構文
`try..catch` 構造は2つのメインブロックを持っています: `try` と `catch` です。:
+=======
+# Error handling, "try...catch"
+
+No matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.
+
+Usually, a script "dies" (immediately stops) in case of an error, printing it to console.
+
+But there's a syntax construct `try...catch` that allows us to "catch" errors so the script can, instead of dying, do something more reasonable.
+
+## The "try...catch" syntax
+
+The `try...catch` construct has two main blocks: `try`, and then `catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
@@ -22,6 +36,7 @@ try {
}
```
+<<<<<<< HEAD
それは次のように動作します:
1. まず、`try {...}` のコードが実行されます。
@@ -35,23 +50,50 @@ try {
いくつか例を見てみましょう。
- エラーなしの例: `alert` `(1)` と `(2)` を表示します:
+=======
+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 goes on, skipping `catch`.
+3. If an error occurs, then the `try` execution is stopped, and control flows to the beginning of `catch (err)`. The `err` variable (we can use any name for it) will contain an error object with details about what happened.
+
+
+
+So, an error inside the `try {...}` block does not kill the script -- we have a chance to handle it in `catch`.
+
+Let's look at some examples.
+
+- An errorless example: shows `alert` `(1)` and `(2)`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
alert('Start of try runs'); // *!*(1) <--*/!*
+<<<<<<< HEAD
// ...ここではエラーはありません
alert('End of try runs'); // *!*(2) <--*/!*
} catch(err) {
+=======
+ // ...no errors here
+
+ alert('End of try runs'); // *!*(2) <--*/!*
+
+ } catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert('Catch is ignored, because there are no errors'); // (3)
}
```
+<<<<<<< HEAD
- エラーの例: `(1)` と `(3)` を表示します:
+=======
+- An example with an error: shows `(1)` and `(3)`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
@@ -59,32 +101,54 @@ try {
alert('Start of try runs'); // *!*(1) <--*/!*
*!*
+<<<<<<< HEAD
lalala; // エラー, 変数は宣言されていません!
+=======
+ lalala; // error, variable is not defined!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert('End of try (never reached)'); // (2)
+<<<<<<< HEAD
} catch(err) {
alert(`Error has occured!`); // *!*(3) <--*/!*
+=======
+ } catch (err) {
+
+ alert(`Error has occurred!`); // *!*(3) <--*/!*
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
```
+<<<<<<< HEAD
````warn header="`try..catch` は実行時エラーにのみ作用します"
`try..catch` を動作させるために、コードは実行可能でなければなりません。つまり、有効なJavaScriptである必要があります。
もしコードが構文的に誤っている場合には動作しません。例えば次は角括弧の不一致です:
+=======
+````warn header="`try...catch` only works for runtime errors"
+For `try...catch` to work, the code must be runnable. In other words, it should be valid JavaScript.
+
+It won't work if the code is syntactically wrong, for instance it has unmatched curly braces:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
{{{{{{{{{{{{
+<<<<<<< HEAD
} catch(e) {
+=======
+} catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert("The engine can't understand this code, it's invalid");
}
```
+<<<<<<< HEAD
JavaScriptエンジンは最初にコードを読み、次にそれを実行します。読み込みのフェーズで発生したエラーは "解析時間(parse-time)" エラーと呼ばれ、回復不能です(コードの内部からは)。なぜなら、エンジンはそのコードを理解することができないからです。
そのため、`try..catch` は有効なコードの中で起きたエラーのみを扱うことができます。このようなエラーは "ランタイムエラー" または "例外" と呼ばれます。
@@ -93,17 +157,34 @@ JavaScriptエンジンは最初にコードを読み、次にそれを実行し
````warn header="`try..catch` は同期的に動作します"
もし `setTimeout` の中のような "スケジュールされた" コードで例外が発生した場合、`try..catch` はそれをキャッチしません。:
+=======
+The JavaScript engine first reads the code, and then runs it. The errors that occur on the reading phase are called "parse-time" errors and are unrecoverable (from inside that code). That's because the engine can't understand the code.
+
+So, `try...catch` can only handle errors that occur in valid code. Such errors are called "runtime errors" or, sometimes, "exceptions".
+````
+
+
+````warn header="`try...catch` works synchronously"
+If an exception happens in "scheduled" code, like in `setTimeout`, then `try...catch` won't catch it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
setTimeout(function() {
+<<<<<<< HEAD
noSuchVariable; // スクリプトはここで死にます
}, 1000);
} catch (e) {
+=======
+ noSuchVariable; // script will die here
+ }, 1000);
+} catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( "won't work" );
}
```
+<<<<<<< HEAD
`try..catch` は実際には関数をスケジュールする `setTimeout` 呼び出しをラップするためです。しかし関数自身は後で実行され、その時エンジンはすでに `try..catch` 構造を抜けています。
スケジュールされた関数の内側の例外をキャッチするためには、その関数の中に `try..catch` が必要です。:
@@ -112,24 +193,45 @@ setTimeout(function() {
try {
noSuchVariable; // try..catch がエラーをハンドリングします!
} catch (e) {
+=======
+That's because the function itself is executed later, when the engine has already left the `try...catch` construct.
+
+To catch an exception inside a scheduled function, `try...catch` must be inside that function:
+```js run
+setTimeout(function() {
+ try {
+ noSuchVariable; // try...catch handles the error!
+ } catch {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( "error is caught here!" );
}
}, 1000);
```
````
+<<<<<<< HEAD
## エラーオブジェクト
エラーが発生したとき、JavaScript はその詳細を含めたオブジェクトを生成します。そして `catch` の引数として渡されます。:
+=======
+## Error object
+
+When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to `catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
// ...
+<<<<<<< HEAD
} catch(err) { // <-- "エラーオブジェクト", err の代わりに別の名前を使うこともできます
+=======
+} catch (err) { // <-- the "error object", could use another word instead of err
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// ...
}
```
+<<<<<<< HEAD
すべての組み込みのエラーに対して、`catch` ブロック内のエラーオブジェクトは2つの主なプロパティを持っています。:
`name`
@@ -144,10 +246,27 @@ try {
: 現在のコールスタックです: エラーに繋がったネスト呼び出しのシーケンスに関する情報を持つ文字列です。デバッグ目的で使われます。
例:
+=======
+For all built-in errors, the error object has two main properties:
+
+`name`
+: Error name. For instance, for an undefined variable that's `"ReferenceError"`.
+
+`message`
+: Textual message about error details.
+
+There are other non-standard properties available in most environments. One of most widely used and supported is:
+
+`stack`
+: Current call stack: a string with information about the sequence of nested calls that led to the error. Used for debugging purposes.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run untrusted
try {
*!*
+<<<<<<< HEAD
lalala; // エラー, 変数が宣言されていません!
*/!*
} catch(err) {
@@ -157,24 +276,48 @@ try {
// 全体としてエラーを表示する事もできます
// エラーは "name: message" として文字列に変換されます
+=======
+ lalala; // error, variable is not defined!
+*/!*
+} catch (err) {
+ alert(err.name); // ReferenceError
+ alert(err.message); // lalala is not defined
+ 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"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(err); // ReferenceError: lalala is not defined
}
```
+<<<<<<< HEAD
## 任意の "catch" バインディング
[recent browser=new]
エラーの詳細が必要ない場合、`catch` はそれを省略できます:
+=======
+## Optional "catch" binding
+
+[recent browser=new]
+
+If we don't need error details, `catch` may omit it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
// ...
+<<<<<<< HEAD
} catch { // <-- (err) なし
+=======
+} catch { // <-- without (err)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// ...
}
```
+<<<<<<< HEAD
## "try..catch" の利用
`try..catch` の実際のユースケースについて探索してみましょう。
@@ -193,10 +336,31 @@ let user = JSON.parse(json); // テキスト表現をJSオブジェクトに変
*/!*
// 今、 user 文字列からプロパティを持つオブジェクトです
+=======
+## Using "try...catch"
+
+Let's explore a real-life use case of `try...catch`.
+
+As we already know, JavaScript supports the [JSON.parse(str)](mdn:js/JSON/parse) method to read JSON-encoded values.
+
+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:
+
+```js run
+let json = '{"name":"John", "age": 30}'; // data from the server
+
+*!*
+let user = JSON.parse(json); // convert the text representation to JS object
+*/!*
+
+// now user is an object with properties from the string
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( user.name ); // John
alert( user.age ); // 30
```
+<<<<<<< HEAD
JSON に関する詳細な情報は、チャプター を参照してください。
**`json` が不正な形式の場合、`JSON.parse` はエラーになるのでスクリプトは "死にます"。**
@@ -206,6 +370,17 @@ JSON に関する詳細な情報は、チャプター を参照し
この方法だと、もしデータが何か間違っている場合、訪問者はそれを知ることができません(開発者コンソールを開かない限り)。また、人々は、エラーメッセージなしで何かが "単に死んでいる" ことを本当に本当に嫌います。
エラーを扱うために `try..catch` を使いましょう。:
+=======
+You can find more detailed information about JSON in the chapter.
+
+**If `json` is malformed, `JSON.parse` generates an error, so the script "dies".**
+
+Should we be satisfied with that? Of course not!
+
+This way, if something's wrong with the data, the visitor will never know that (unless they open the developer console). And people really don't like when something "just dies" without any error message.
+
+Let's use `try...catch` to handle the error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let json = "{ bad json }";
@@ -213,6 +388,7 @@ let json = "{ bad json }";
try {
*!*
+<<<<<<< HEAD
let user = JSON.parse(json); // <-- エラーが起きたとき...
*/!*
alert( user.name ); // 動作しません
@@ -223,10 +399,23 @@ try {
alert( "Our apologies, the data has errors, we'll try to request it one more time." );
alert( e.name );
alert( e.message );
+=======
+ let user = JSON.parse(json); // <-- when an error occurs...
+*/!*
+ alert( user.name ); // doesn't work
+
+} catch (err) {
+*!*
+ // ...the execution jumps here
+ alert( "Our apologies, the data has errors, we'll try to request it one more time." );
+ alert( err.name );
+ alert( err.message );
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
```
+<<<<<<< HEAD
ここでは、メッセージを表示するためのだけに `catch` ブロックを使っていますが、より多くのことをすることができます。: 新たなネットワーク要求、訪問者への代替手段の提案、ロギング機構へエラーに関する情報の送信... すべて、単に死ぬよりははるかに良いです。
## 独自のエラーをスローする
@@ -246,10 +435,32 @@ try {
*/!*
} catch (e) {
+=======
+Here we use the `catch` block only to show the message, but we can do much more: send a new network request, suggest an alternative to the visitor, send information about the error to a logging facility, ... . All much better than just dying.
+
+## Throwing our own errors
+
+What if `json` is syntactically correct, but doesn't have a required `name` property?
+
+Like this:
+
+```js run
+let json = '{ "age": 30 }'; // incomplete data
+
+try {
+
+ let user = JSON.parse(json); // <-- no errors
+*!*
+ alert( user.name ); // no name!
+*/!*
+
+} catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( "doesn't execute" );
}
```
+<<<<<<< HEAD
ここで、`JSON.parse` は通常どおり実行しますが、`"name"` の欠落は実際には我々にとってはエラーです。
エラー処理を統一するために、`throw` 演算子を使います。
@@ -259,16 +470,35 @@ try {
`throw` 演算子はエラーを生成します。
構文は次の通りです:
+=======
+Here `JSON.parse` runs normally, but the absence of `name` is actually an error for us.
+
+To unify error handling, we'll use the `throw` operator.
+
+### "Throw" operator
+
+The `throw` operator generates an error.
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
throw
```
+<<<<<<< HEAD
技術的には、エラーオブジェクトとしてなんでも使うことができます。たとえ、数値や文字列のようなプリミティブでもOKです。しかし、`name` と `message` プロパティを持つオブジェクトを使うのがベターです(組み込みのエラーと互換性をいくらか保つために)。
JavaScriptは標準エラーのための多くの組み込みのコンストラクタを持っています: `Error`, `SyntaxError`, `ReferenceError`, `TypeError` などです。我々もエラーオブジェクトを作るのにそれらが使えます。
構文は次の通りです:
+=======
+Technically, we can use anything as an error object. That may be even a primitive, like a number or a string, but it's better to use objects, preferably with `name` and `message` properties (to stay somewhat compatible with built-in errors).
+
+JavaScript has many built-in constructors for standard errors: `Error`, `SyntaxError`, `ReferenceError`, `TypeError` and others. We can use them to create error objects as well.
+
+Their syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let error = new Error(message);
@@ -278,9 +508,15 @@ let error = new ReferenceError(message);
// ...
```
+<<<<<<< HEAD
組み込みのエラー(任意のオブジェクトではなく、エラーのみ)では、`name` プロパティはコンストラクタの名前と全く同じになります。そして `message` は引数から取られます。
例:
+=======
+For built-in errors (not for any objects, just for errors), the `name` property is exactly the name of the constructor. And `message` is taken from the argument.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let error = new Error("Things happen o_O");
@@ -289,11 +525,16 @@ alert(error.name); // Error
alert(error.message); // Things happen o_O
```
+<<<<<<< HEAD
`JSON.parse` が生成するエラーの種類を見てみましょう:
+=======
+Let's see what kind of error `JSON.parse` generates:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
JSON.parse("{ bad json o_O }");
+<<<<<<< HEAD
} catch(e) {
*!*
alert(e.name); // SyntaxError
@@ -314,6 +555,28 @@ let json = '{ "age": 30 }'; // 不完全なデータ
try {
let user = JSON.parse(json); // <-- エラーなし
+=======
+} catch (err) {
+*!*
+ alert(err.name); // SyntaxError
+*/!*
+ alert(err.message); // Unexpected token b in JSON at position 2
+}
+```
+
+As we can see, that's a `SyntaxError`.
+
+And in our case, the absence of `name` is an error, as users must have a `name`.
+
+So let's throw it:
+
+```js run
+let json = '{ "age": 30 }'; // incomplete data
+
+try {
+
+ let user = JSON.parse(json); // <-- no errors
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
if (!user.name) {
*!*
@@ -323,6 +586,7 @@ try {
alert( user.name );
+<<<<<<< HEAD
} catch(e) {
alert( "JSON Error: " + e.message ); // JSON Error: Incomplete data: no name
}
@@ -366,6 +630,51 @@ try {
3. どう処理すればいいか分からなければ、`throw err` をします。
通常は、`instanceof` 演算子を使用してエラーの種類がチェックできます。:
+=======
+} catch (err) {
+ alert( "JSON Error: " + err.message ); // JSON Error: Incomplete data: no name
+}
+```
+
+In the line `(*)`, the `throw` operator generates a `SyntaxError` with the given `message`, the same way as JavaScript would generate it itself. The execution of `try` immediately stops and the control flow jumps into `catch`.
+
+Now `catch` became a single place for all error handling: both for `JSON.parse` and other cases.
+
+## Rethrowing
+
+In the example above we use `try...catch` to handle incorrect data. But is it possible that *another unexpected error* occurs within the `try {...}` block? Like a programming error (variable is not defined) or something else, not just this "incorrect data" thing.
+
+For example:
+
+```js run
+let json = '{ "age": 30 }'; // incomplete data
+
+try {
+ user = JSON.parse(json); // <-- forgot to put "let" before user
+
+ // ...
+} catch (err) {
+ alert("JSON Error: " + err); // JSON Error: ReferenceError: user is not defined
+ // (no JSON Error actually)
+}
+```
+
+Of course, everything's possible! Programmers do make mistakes. Even in open-source utilities used by millions for decades -- suddenly a bug may be discovered that leads to terrible hacks.
+
+In our case, `try...catch` is placed to catch "incorrect data" errors. But by its nature, `catch` gets *all* errors from `try`. Here it gets an unexpected error, but still shows the same `"JSON Error"` message. That's wrong and also makes the code more difficult to debug.
+
+To avoid such problems, we can employ the "rethrowing" technique. The rule is simple:
+
+**Catch should only process errors that it knows and "rethrow" all others.**
+
+The "rethrowing" technique can be explained in more detail as:
+
+1. Catch gets all errors.
+2. In the `catch (err) {...}` block we analyze the error object `err`.
+3. If we don't know how to handle it, we do `throw err`.
+
+Usually, we can check the error type using the `instanceof` operator:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
@@ -374,17 +683,30 @@ try {
*!*
if (err instanceof ReferenceError) {
*/!*
+<<<<<<< HEAD
alert('ReferenceError'); // 未定義変数へのアクセスに対する "ReferenceError"
+=======
+ alert('ReferenceError'); // "ReferenceError" for accessing an undefined variable
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
また、`erro.name` プロパティから、エラークラス名を取得することも可能です。すべてのネイティブエラーはエラークラス名があります。もう1つの選択肢は、`err.constructor.name` を参照することです。
下のコードでは、`catch` が `SyntaxError` だけを処理するよう再スローを使っています。:
```js run
let json = '{ "age": 30 }'; // 不完全なデータ
+=======
+We can also get the error class name from `err.name` property. All native errors have it. Another option is to read `err.constructor.name`.
+
+In the code below, we use rethrowing so that `catch` only handles `SyntaxError`:
+
+```js run
+let json = '{ "age": 30 }'; // incomplete data
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
try {
let user = JSON.parse(json);
@@ -394,11 +716,16 @@ try {
}
*!*
+<<<<<<< HEAD
blabla(); // 予期しないエラー
+=======
+ blabla(); // unexpected error
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert( user.name );
+<<<<<<< HEAD
} catch(e) {
*!*
@@ -406,17 +733,34 @@ try {
alert( "JSON Error: " + e.message );
} else {
throw e; // 再スロー (*)
+=======
+} catch (err) {
+
+*!*
+ if (err instanceof SyntaxError) {
+ alert( "JSON Error: " + err.message );
+ } else {
+ throw err; // rethrow (*)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
*/!*
}
```
+<<<<<<< HEAD
行 `(*)` での、`catch` ブロック内部からのエラーのスローは `try..catch` を "抜けて" 外部の `try..catch` 構造(存在する場合)でキャッチされる、またはスクリプトをキルします。
従って、`catch` ブロックは実際に扱い方を知っているエラーだけを処理しその他すべてを "スキップ" します。
下の例は、このようなエラーが1つ上のレベルの `try..catch` で捕捉されるデモです:
+=======
+The error throwing on line `(*)` from inside `catch` block "falls out" of `try...catch` and can be either caught by an outer `try...catch` construct (if it exists), or it kills the script.
+
+So the `catch` block actually handles only errors that it knows how to deal with and "skips" all others.
+
+The example below demonstrates how such errors can be caught by one more level of `try...catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function readData() {
@@ -427,11 +771,19 @@ function readData() {
*!*
blabla(); // error!
*/!*
+<<<<<<< HEAD
} catch (e) {
// ...
if (e.name != 'SyntaxError') {
*!*
throw e; // 再スロー (今のエラーの扱い方を知らない)
+=======
+ } catch (err) {
+ // ...
+ if (!(err instanceof SyntaxError)) {
+*!*
+ throw err; // rethrow (don't know how to deal with it)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
}
@@ -439,13 +791,20 @@ function readData() {
try {
readData();
+<<<<<<< HEAD
} catch (e) {
*!*
alert( "External catch got: " + e ); // caught it!
+=======
+} catch (err) {
+*!*
+ alert( "External catch got: " + err ); // caught it!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
```
+<<<<<<< HEAD
ここでは、`readData` は `SyntaxError` の処理の仕方だけ知っており、外部の `try..catch` はすべての処理の方法を知っています。
## try..catch..finally
@@ -472,18 +831,51 @@ try {
```
このコードを実行してみましょう。:
+=======
+Here `readData` only knows how to handle `SyntaxError`, while the outer `try...catch` knows how to handle everything.
+
+## try...catch...finally
+
+Wait, that's not all.
+
+The `try...catch` construct may have one more code clause: `finally`.
+
+If it exists, it runs in all cases:
+
+- after `try`, if there were no errors,
+- after `catch`, if there were errors.
+
+The extended syntax looks like this:
+
+```js
+*!*try*/!* {
+ ... try to execute the code ...
+} *!*catch*/!* (err) {
+ ... handle errors ...
+} *!*finally*/!* {
+ ... execute always ...
+}
+```
+
+Try running this code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
try {
alert( 'try' );
if (confirm('Make an error?')) BAD_CODE();
+<<<<<<< HEAD
} catch (e) {
+=======
+} catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( 'catch' );
} finally {
alert( 'finally' );
}
```
+<<<<<<< HEAD
このコードは2つの実行方法があります。:
1. もし "Make an error" に "Yes" と答えると、`try -> catch -> finally` となります。
@@ -496,6 +888,20 @@ try {
`finally` 句は何があっても計測を完了させるのに良い場所です。
ここで、`finally` は両方のシチュエーション -- `fib` の実行が成功するケースと失敗するケース -- で時間が正しく計測されることを保証します。:
+=======
+The code has two ways of execution:
+
+1. If you answer "Yes" to "Make an error?", then `try -> catch -> finally`.
+2. If you say "No", then `try -> finally`.
+
+The `finally` clause is often used when we start doing something and want to finalize it in any case of outcome.
+
+For instance, we want to measure the time that a Fibonacci numbers function `fib(n)` takes. Naturally, we can start measuring before it runs and finish afterwards. But what if there's an error during the function call? In particular, the implementation of `fib(n)` in the code below returns an error for negative or non-integer numbers.
+
+The `finally` clause is a great place to finish the measurements no matter what.
+
+Here `finally` guarantees that the time will be measured correctly in both situations -- in case of a successful execution of `fib` and in case of an error in it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let num = +prompt("Enter a positive integer number?", 35)
@@ -513,7 +919,11 @@ let start = Date.now();
try {
result = fib(num);
+<<<<<<< HEAD
} catch (e) {
+=======
+} catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
result = 0;
*!*
} finally {
@@ -521,11 +931,16 @@ try {
}
*/!*
+<<<<<<< HEAD
alert(result || "error occured");
+=======
+alert(result || "error occurred");
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( `execution took ${diff}ms` );
```
+<<<<<<< HEAD
コードを実行して `prompt` に `35` を入力することで確認できます -- 通常 `try` の後に `finally` を実行します。そして `-1` を入れると -- すぐにエラーになり、その実行は `0ms` となります。両方の計測は正しく行われています。
つまり、関数を終了するには方法が2つあります: `return` または `throw` です。 `finally` 句はそれら両方とも処理します。
@@ -541,6 +956,23 @@ alert( `execution took ${diff}ms` );
Finally 句は `try..catch` からの *任意の* 終了に対して機能します。それは明白な `return` も含みます。
下の例では、`try` の中で `return` があります。この場合、`finally` は制御が外部コードに戻る前に実行されます。
+=======
+You can check by running the code with entering `35` into `prompt` -- it executes normally, `finally` after `try`. And then enter `-1` -- there will be an immediate error, and the execution will take `0ms`. Both measurements are done correctly.
+
+In other words, the function may finish with `return` or `throw`, that doesn't matter. The `finally` clause executes in both cases.
+
+
+```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 we declared `let` in `try` block, it would only be visible inside of it.
+```
+
+````smart header="`finally` and `return`"
+The `finally` clause works for *any* exit from `try...catch`. That includes an explicit `return`.
+
+In the example below, there's a `return` in `try`. In this case, `finally` is executed just before the control returns to the outer code.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function func() {
@@ -550,7 +982,11 @@ function func() {
return 1;
*/!*
+<<<<<<< HEAD
} catch (e) {
+=======
+ } catch (err) {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
/* ... */
} finally {
*!*
@@ -559,6 +995,7 @@ function func() {
}
}
+<<<<<<< HEAD
alert( func() ); // 最初に finally の alert が動作し、次にこれが動作します
```
````
@@ -593,6 +1030,42 @@ function func() {
仕様ではそのようなものはありませんが、通常、環境がそれを提供しています。なぜなら本当に有用だからです。例えば、Node.js はそのために [process.on('uncaughtException')](https://nodejs.org/api/process.html#process_event_uncaughtexception)を持っています。また、ブラウザでは関数を特別な [window.onerror](mdn:api/GlobalEventHandlers/onerror) プロパティに代入することができます。それはキャッチしていないエラーの場合に実行されます。
構文:
+=======
+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 here (let them fall through), but want to be sure that processes that we started are finalized.
+
+```js
+function func() {
+ // start doing something that needs completion (like measurements)
+ try {
+ // ...
+ } finally {
+ // complete that thing even if all dies
+ }
+}
+```
+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
+
+```warn header="Environment-specific"
+The information from this section is not a part of the core JavaScript.
+```
+
+Let's imagine we've got a fatal error outside of `try...catch`, and the script died. Like a programming error or some other terrible thing.
+
+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 the special [window.onerror](mdn:api/GlobalEventHandlers/onerror) property, that will run in case of an uncaught error.
+
+The syntax:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
window.onerror = function(message, url, line, col, error) {
@@ -601,6 +1074,7 @@ window.onerror = function(message, url, line, col, error) {
```
`message`
+<<<<<<< HEAD
: エラーメッセージ
`url`
@@ -613,6 +1087,20 @@ window.onerror = function(message, url, line, col, error) {
: エラーオブジェクト
例:
+=======
+: Error message.
+
+`url`
+: URL of the script where error happened.
+
+`line`, `col`
+: Line and column numbers where error happened.
+
+`error`
+: Error object.
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```html run untrusted refresh height=1
```
+<<<<<<< HEAD
グローバルハンドラー `window.onerror` の役割は、通常スクリプトの実行の回復ではありません -- プログラミングエラーの場合、恐らくそれは不可能なので開発者にエラーメッセージを送ります。
このようなケースでエラーログを提供する web サービスもあります。https://errorception.com> や 。
@@ -673,3 +1166,48 @@ try {
*再スロー* はエラーハンドリングの非常に重要なパターンです。: `catch` ブロックは通常、特定のエラータイプを処理する方法を予期し、知っています。したがって、知らないエラーは再スローすべきです。
たとえ `try..catch` を持っていない場合でも、ほとんどの環境では "抜け出た" エラーをキャッチするために "グローバル" なエラーハンドラを設定することができます。ブラウザでは、それは `window.onerror` です。
+=======
+The role of the global handler `window.onerror` is usually not to recover the script execution -- that's probably impossible in case of programming errors, but to send the error message to developers.
+
+There are also web-services that provide error-logging for such cases, like or .
+
+They work like this:
+
+1. We register at the service and get a piece of JS (or a script URL) from them to insert on pages.
+2. That JS script sets a custom `window.onerror` function.
+3. When an error occurs, it sends a network request about it to the service.
+4. We can log in to the service web interface and see errors.
+
+## Summary
+
+The `try...catch` construct allows to handle runtime errors. It literally allows to "try" running the code and "catch" errors that may occur in it.
+
+The syntax is:
+
+```js
+try {
+ // run this code
+} catch (err) {
+ // if an error happened, then jump here
+ // err is the error object
+} finally {
+ // do in any case after try/catch
+}
+```
+
+There may be no `catch` section or no `finally`, so shorter constructs `try...catch` and `try...finally` are also valid.
+
+Error objects have following properties:
+
+- `message` -- the human-readable error message.
+- `name` -- the string with error name (error constructor name).
+- `stack` (non-standard, but well-supported) -- the stack at the moment of error creation.
+
+If an error object is not needed, we can omit it by using `catch {` instead of `catch (err) {`.
+
+We can also generate our own errors using the `throw` operator. Technically, the argument of `throw` can be anything, but usually it's an error object inheriting from the built-in `Error` class. More on extending errors in the next chapter.
+
+*Rethrowing* is a very important pattern of error handling: a `catch` block usually expects and knows how to handle the particular error type, so it should rethrow errors it doesn't know.
+
+Even if we don't have `try...catch`, most environments allow us to setup a "global" error handler to catch errors that "fall out". In-browser, that's `window.onerror`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/10-error-handling/2-custom-errors/1-format-error/solution.md b/1-js/10-error-handling/2-custom-errors/1-format-error/solution.md
index bb6b74cfaf..754e68f9a4 100644
--- a/1-js/10-error-handling/2-custom-errors/1-format-error/solution.md
+++ b/1-js/10-error-handling/2-custom-errors/1-format-error/solution.md
@@ -2,7 +2,7 @@
class FormatError extends SyntaxError {
constructor(message) {
super(message);
- this.name = "FormatError";
+ this.name = this.constructor.name;
}
}
diff --git a/1-js/10-error-handling/2-custom-errors/1-format-error/task.md b/1-js/10-error-handling/2-custom-errors/1-format-error/task.md
index 88364688c3..8bb3928fe7 100644
--- a/1-js/10-error-handling/2-custom-errors/1-format-error/task.md
+++ b/1-js/10-error-handling/2-custom-errors/1-format-error/task.md
@@ -2,6 +2,7 @@ importance: 5
---
+<<<<<<< HEAD
# SyntaxError を継承する
組み込みの `SyntaxError` クラスを継承した `FormatError` クラスを作りなさい。
@@ -9,6 +10,15 @@ importance: 5
`message`, `name` と `stack` プロパティをサポートする必要があります。
使用例:
+=======
+# Inherit from SyntaxError
+
+Create a class `FormatError` that inherits from the built-in `SyntaxError` class.
+
+It should support `message`, `name` and `stack` properties.
+
+Usage example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let err = new FormatError("formatting error");
@@ -18,5 +28,9 @@ alert( err.name ); // FormatError
alert( err.stack ); // stack
alert( err instanceof FormatError ); // true
+<<<<<<< HEAD
alert( err instanceof SyntaxError ); // true (SyntaxError を継承しているので)
+=======
+alert( err instanceof SyntaxError ); // true (because inherits from SyntaxError)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
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 242cd26484..17b5de3aae 100644
--- a/1-js/10-error-handling/2-custom-errors/article.md
+++ b/1-js/10-error-handling/2-custom-errors/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# カスタムエラー, Error の拡張
開発する際、タスクで上手くいかない可能性のある特定の物事を反映するために、独自のエラークラスが必要になることがよくあります。ネットワーク操作のエラーであれば、`HttpError`、データベース操作は `DbError`、検索操作の場合は`NotFoundError` などが必要な場合があります。
@@ -13,10 +14,28 @@ JavaScript は任意の引数で `throw` できるので、技術的にはカス
例として、ユーザデータをもつ JSON を読む関数 `readUser(json)` を考えてみましょう。
ここでは、有効な `json` がどのように見えるかの例を示します。:
+=======
+# Custom errors, extending Error
+
+When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks. For errors in network operations we may need `HttpError`, for database operations `DbError`, for searching operations `NotFoundError` and so on.
+
+Our errors should support basic error properties like `message`, `name` and, preferably, `stack`. But they also may have other properties of their own, e.g. `HttpError` objects may have a `statusCode` property with a value like `404` or `403` or `500`.
+
+JavaScript allows to use `throw` with any argument, so technically our custom error classes don't need to inherit from `Error`. But if we inherit, then it becomes possible to use `obj instanceof Error` to identify error objects. So it's better to inherit from it.
+
+As the application grows, our own errors naturally form a hierarchy. For instance, `HttpTimeoutError` may inherit from `HttpError`, and so on.
+
+## Extending Error
+
+As an example, let's consider a function `readUser(json)` that should read JSON with user data.
+
+Here's an example of how a valid `json` may look:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let json = `{ "name": "John", "age": 30 }`;
```
+<<<<<<< HEAD
内部的には、`JSON.parse` を使います。不正な `json` を受け取った場合は `SyntaxError` をスローします。しかし、たとえ `json` が構文的に正しくても、それが正しいユーザとは限りません。その `json` には必要なデータが不足しているかもしれません。例えば、上のケースだと、ユーザに必要不可欠な `name` や `age` プロパティを持っていない場合です。
私たちの関数 `readUser(json)` はJSONを読むだけでなく、データのチェック(バリデート)をします。必須のフィールドがなかったり、フォーマットが誤っている場合はエラーになります。そしてそれは `SyntaxError` ではありません。なぜならデータは構文的には正しく、別の種類のエラーだからです。したがって、このエラーは `ValidationError` と呼び、そのためのクラスを作りましょう。このようなエラーは、問題のあるフィールドに関する情報も保持する必要があります。
@@ -32,13 +51,36 @@ class Error {
this.message = message;
this.name = "Error"; // (組み込みのエラークラスごとに異なる名前)
this.stack = ; // 非標準ですが、ほとんどの環境はサポートしています
+=======
+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 `Error` class.
+
+The `Error` class is built-in, but here's its approximate code so we can understand what we're extending:
+
+```js
+// The "pseudocode" for the built-in Error class defined by JavaScript itself
+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
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
では、`ValidationError` をそれから継承させ、動かしましょう:
```js run untrusted
+=======
+Now let's inherit `ValidationError` from it and try it in action:
+
+```js run
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
class ValidationError extends Error {
*/!*
@@ -57,6 +99,7 @@ try {
} catch(err) {
alert(err.message); // Whoops!
alert(err.name); // ValidationError
+<<<<<<< HEAD
alert(err.stack); // それぞれの行番号を持つネストされたコールのリスト
}
```
@@ -66,6 +109,17 @@ try {
親のコンストラクタは `name` プロパティも `"Error"` へセットしますので、行 `(2)` で正しい値にリセットしています。
`readUser(json)` で使ってみましょう:
+=======
+ alert(err.stack); // a list of nested calls with line numbers for each
+}
+```
+
+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.
+
+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)`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class ValidationError extends Error {
@@ -89,7 +143,11 @@ function readUser(json) {
return user;
}
+<<<<<<< HEAD
// try..catch での動作例
+=======
+// Working example with try..catch
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
try {
let user = readUser('{ "age": 25 }');
@@ -101,11 +159,16 @@ try {
} else if (err instanceof SyntaxError) { // (*)
alert("JSON Syntax Error: " + err.message);
} else {
+<<<<<<< HEAD
throw err; // 知らないエラーなので、再スロー (**)
+=======
+ throw err; // unknown error, rethrow it (**)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
上のコードの `try..catch` ブロックは `ValidationError` と `JSON.parse` からの組み込みの `SyntaxError` 両方を処理します。
行 `(*)` で特定のエラーの種類をチェックするために、どのように `instanceof` を使っているか見てください。
@@ -126,6 +189,28 @@ try {
## さらなる継承
`ValidationError` クラスはとても汎用的です。色んな種類の誤りがあります。例えば、プロパティが存在しなかったり、誤ったフォーマット(`age` が文字列値のような)など。ここで、存在しないプロパティに対するより具体的なクラス `PropertyRequiredError` を作りましょう。欠落しているプロパティについての追加の情報を保持します。
+=======
+The `try..catch` block in the code above handles both our `ValidationError` and the built-in `SyntaxError` from `JSON.parse`.
+
+Please take a look at how we use `instanceof` to check for the specific error type in the line `(*)`.
+
+We could also look at `err.name`, like this:
+
+```js
+// ...
+// instead of (err instanceof SyntaxError)
+} else if (err.name == "SyntaxError") { // (*)
+// ...
+```
+
+The `instanceof` version is much better, because in the future we are going to extend `ValidationError`, make subtypes of it, like `PropertyRequiredError`. And `instanceof` check will continue to work for new inheriting classes. So that's future-proof.
+
+Also it's important that if `catch` meets an unknown error, then it rethrows it in the line `(**)`. The `catch` block only knows how to handle validation and syntax errors, other kinds (caused by a typo in the code or other unknown reasons) should fall through.
+
+## Further inheritance
+
+The `ValidationError` class is very generic. Many things may go wrong. The property may be absent or it may be in a wrong format (like a string value for `age` instead of a number). Let's make a more concrete class `PropertyRequiredError`, exactly for absent properties. It will carry additional information about the property that's missing.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class ValidationError extends Error {
@@ -145,7 +230,11 @@ class PropertyRequiredError extends ValidationError {
}
*/!*
+<<<<<<< HEAD
// 使用法
+=======
+// Usage
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
function readUser(json) {
let user = JSON.parse(json);
@@ -159,7 +248,11 @@ function readUser(json) {
return user;
}
+<<<<<<< HEAD
// try..catch での動作例
+=======
+// Working example with try..catch
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
try {
let user = readUser('{ "age": 25 }');
@@ -173,11 +266,16 @@ try {
} else if (err instanceof SyntaxError) {
alert("JSON Syntax Error: " + err.message);
} else {
+<<<<<<< HEAD
throw err; // 知らないエラーなので、それを再スロー
+=======
+ throw err; // unknown error, rethrow it
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
新しいクラス `PropertyRequiredError` は簡単に使えます。プロパティ名を渡すだけです。: `new PropertyRequiredError(property)`。人が読める `message` はコンストラクタで作られます。
`PropertyRequiredError` コンストラクタでの `this.name` は再度手動で割り当てられることに注目してください。カスタムのエラーを作る度に `this.name = ` と代入することには、少しうんざりするかもしれません。が、`this.name = this.constructor.name` を行う "基本エラー" クラスを作り、カスタムエラーはそれを継承することで避けることができます。
@@ -185,6 +283,15 @@ try {
これを `MyError` と呼びましょう。
ここでは、単純化した `MyError` のコードと他のカスタムエラークラスを示します。:
+=======
+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. We can avoid it by making our own "basic error" class that assigns `this.name = this.constructor.name`. And then inherit all our custom errors from it.
+
+Let's call it `MyError`.
+
+Here's the code with `MyError` and other custom error classes, simplified:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class MyError extends Error {
@@ -209,6 +316,7 @@ class PropertyRequiredError extends ValidationError {
alert( new PropertyRequiredError("field").name ); // PropertyRequiredError
```
+<<<<<<< HEAD
これで、カスタムエラーははるかに短くなりました。特に `ValidationError` はコンストラクタの `"this.name = ..."` の行を除いたので。
## 例外のラッピング
@@ -218,10 +326,22 @@ alert( new PropertyRequiredError("field").name ); // PropertyRequiredError
`readUser` を呼び出すコードは、これらのエラーを処理する必要があります。今は `catch` ブロックの中で、異なるエラータイプのチェックと未知のエラーを再スローするために、複数の `if` を使っています。
スキーマはこのようになります:
+=======
+Now custom errors are much shorter, especially `ValidationError`, as we got rid of the `"this.name = ..."` line in the constructor.
+
+## Wrapping exceptions
+
+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`s in the `catch` block, that check the class and handle known errors and rethrow the unknown ones.
+
+The scheme is like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
try {
...
+<<<<<<< HEAD
readUser() // 潜在的なエラーの原因
...
} catch (err) {
@@ -231,10 +351,22 @@ try {
// シンタックスエラーの処理
} else {
throw err; // 未知のエラー、再スロー
+=======
+ readUser() // the potential error source
+ ...
+} catch (err) {
+ if (err instanceof ValidationError) {
+ // handle validation errors
+ } else if (err instanceof SyntaxError) {
+ // handle syntax errors
+ } else {
+ throw err; // unknown error, rethrow it
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
```
+<<<<<<< HEAD
上のコードでは2種類のエラーがありますが、他にもありえます。
もし `readUser` 関数が複数の種類のエラーを生成する場合、`readUser` 呼び出しをするすべてのコードで、毎回本当にすべてのエラータイプを1つずつチェックしたいですか?
@@ -250,6 +382,23 @@ try {
`readUser` を呼び出すコードは、`ReadError` だけをチェックする必要があり、他の種類のデータ読み込みエラーのチェックは不要です。そして、エラーの詳細が必要な場合は、その `cause` プロパティで確認できます。
これは、`ReadError` を定義し、`readUser` と `try..catch` でそれを利用するデモです。:
+=======
+In the code above we can see two types of errors, but there can be more.
+
+If the `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 every time?
+
+Often the answer is "No": we'd like to be "one level above all that". We just want to know if there was a "data reading error" -- why exactly it happened is often irrelevant (the error message describes it). Or, even better, we'd like to have a way to get the error details, but only if we need to.
+
+The technique that we describe here is called "wrapping exceptions".
+
+1. We'll make a new class `ReadError` to represent a generic "data reading" error.
+2. The function `readUser` will catch data reading errors that occur inside it, such as `ValidationError` and `SyntaxError`, and generate a `ReadError` instead.
+3. The `ReadError` object will keep the reference to the original error in its `cause` property.
+
+Then the code that calls `readUser` will only have to check for `ReadError`, not for every kind of data reading errors. And if it needs more details of an error, it can check its `cause` property.
+
+Here's the code that defines `ReadError` and demonstrates its use in `readUser` and `try..catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class ReadError extends Error {
@@ -317,6 +466,7 @@ try {
}
```
+<<<<<<< HEAD
上のコードで、`readUser` は説明されている通りに正確に動作します -- 構文とバリデーションエラーをキャッチし、`ReadError` エラーを代わりにスローします(未知のエラーは通常通り再スローします)。
なので、外部のコードは `instanceof ReadError` をチェックするだけです。可能性のあるすべてのエラータイプをリストする必要はありません。
@@ -328,3 +478,16 @@ try {
- `Error` や他の組み込みのエラークラスから継承することができます。そのときは、`name` プロパティに手を入れることと、`super` の呼び出しを忘れないでください。
- 特定のエラーのチェックには `instanceof` が使えます。これは継承している場合にも有効です。しかし、ときにはサードパーティのライブラリから来たエラーオブジェクトを持っていて、簡単にそのクラスを取得する方法がないことがあります。このような場合には `name` プロパティが使えます。
- 例外のラッピングは広く利用されているテクニックです: 関数が低レベルの例外を処理し、それぞれの低レベルの例外の代わりに高レベルのエラーを生成します。低レベルの例外は、上の例の `err.cause` のようにオブジェクトのプロパティになることがありますが、厳密には必須ではありません。
+=======
+In the code above, `readUser` works exactly as described -- catches syntax and validation errors and throws `ReadError` errors instead (unknown errors are rethrown as usual).
+
+So the outer code checks `instanceof ReadError` and that's it. No need to list all possible error types.
+
+The approach is called "wrapping exceptions", because we take "low level" exceptions and "wrap" them into `ReadError` that is more abstract. It is widely used in object-oriented programming.
+
+## Summary
+
+- We can inherit from `Error` and other built-in error classes normally. We just need to take care of the `name` property and don't forget to call `super`.
+- We can use `instanceof` to check for particular errors. It also works with inheritance. But sometimes we have an error object coming from a 3rd-party library and there's no easy way to get its class. Then `name` property can be used for such checks.
+- Wrapping exceptions is a widespread technique: a function handles low-level exceptions and creates higher-level errors instead of various low-level ones. Low-level exceptions sometimes become properties of that object like `err.cause` in the examples above, but that's not strictly required.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/10-error-handling/index.md b/1-js/10-error-handling/index.md
index abed774f9d..3f43a93959 100644
--- a/1-js/10-error-handling/index.md
+++ b/1-js/10-error-handling/index.md
@@ -1 +1,5 @@
+<<<<<<< HEAD
# エラーハンドリング
+=======
+# Error handling
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/01-callbacks/article.md b/1-js/11-async/01-callbacks/article.md
index 7a282d6744..8b9e9fb267 100644
--- a/1-js/11-async/01-callbacks/article.md
+++ b/1-js/11-async/01-callbacks/article.md
@@ -1,5 +1,6 @@
+<<<<<<< HEAD
# 前置き: コールバック
```warn header="ここの例ではブラウザメソッドを使用します"
@@ -22,12 +23,37 @@
function loadScript(src) {
//
diff --git a/1-js/11-async/04-promise-error-handling/01-error-async/solution.md b/1-js/11-async/04-promise-error-handling/01-error-async/solution.md
index eeb319758b..604fb8bbe0 100644
--- a/1-js/11-async/04-promise-error-handling/01-error-async/solution.md
+++ b/1-js/11-async/04-promise-error-handling/01-error-async/solution.md
@@ -1,4 +1,8 @@
+<<<<<<< HEAD
解答: **いいえ、実行されません**:
+=======
+The answer is: **no, it won't**:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
new Promise(function(resolve, reject) {
@@ -8,6 +12,12 @@ new Promise(function(resolve, reject) {
}).catch(alert);
```
+<<<<<<< HEAD
チャプターの中で言った通り、関数コードの周りには "暗黙の `try..catch`" があります。そのため、すべての同期エラーは処理されます。
しかし、ここではエラーは executor が実行中でなく、その後に生成されます。したがって、promise はそれを処理できません。
+=======
+As said in the chapter, there's an "implicit `try..catch`" around the function code. So all synchronous errors are handled.
+
+But here the error is generated not while the executor is running, but later. So the promise can't handle it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/04-promise-error-handling/01-error-async/task.md b/1-js/11-async/04-promise-error-handling/01-error-async/task.md
index 94f7ed6e33..b4be0f1515 100644
--- a/1-js/11-async/04-promise-error-handling/01-error-async/task.md
+++ b/1-js/11-async/04-promise-error-handling/01-error-async/task.md
@@ -1,6 +1,10 @@
# setTimeout でのエラー
+<<<<<<< HEAD
`.catch` はトリガされると思いますか?またその理由を説明できますか?
+=======
+What do you think? Will the `.catch` trigger? Explain your answer.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
new Promise(function(resolve, reject) {
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 a0737ca086..df27466b09 100644
--- a/1-js/11-async/04-promise-error-handling/article.md
+++ b/1-js/11-async/04-promise-error-handling/article.md
@@ -1,21 +1,38 @@
+<<<<<<< HEAD
# Promise でのエラーハンドリング
promise チェーンはエラーハンドリングに優れています。promise が reject されると、制御は最も近い reject ハンドラに移ります。この動きは実際に非常に便利です。
例えば、下のコードでは URL が誤っており(存在しないサイト)、`.catch` がエラーをハンドリングします:
+=======
+# Error handling with promises
+
+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.
+
+For instance, in the code below the URL to `fetch` is wrong (no such site) and `.catch` handles the error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
fetch('https://no-such-server.blabla') // rejects
*/!*
.then(response => response.json())
+<<<<<<< HEAD
.catch(err => alert(err)) // TypeError: failed to fetch (エラーメッセージ内容は異なる場合があります)
```
ご覧の通り、`.catch` は直後である必要はありません。1つまたは複数の `.then` の後に現れるかもしれません。
また、サイトはすべて問題ありませんが、レスポンスが有効な JSON でない可能性もあります。すべてのエラーをキャッチする最も簡単な方法はチェーンの末尾に `.catch` を追加することです。
+=======
+ .catch(err => alert(err)) // TypeError: failed to fetch (the text may vary)
+```
+
+As you can see, the `.catch` doesn't have to be immediate. It may appear after one or maybe several `.then`.
+
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
fetch('/article/promise-chaining/user.json')
@@ -38,6 +55,7 @@ fetch('/article/promise-chaining/user.json')
*/!*
```
+<<<<<<< HEAD
通常、この `.catch` は呼ばれません。ですが、上の promise のいずれかがreject した場合(ネットワーク問題 or 無効な json など)、それをキャッチします。
## 暗黙の try..catch
@@ -48,12 +66,25 @@ executor と promise ハンドラのコードは "見えない `try..catch`" を
```js run
new Promise(function(resolve, reject) {
+=======
+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
+
+The code of a promise executor and promise handlers has an "invisible `try..catch`" around it. If an exception happens, it gets caught and treated as a rejection.
+
+For instance, this code:
+
+```js run
+new Promise((resolve, reject) => {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
throw new Error("Whoops!");
*/!*
}).catch(alert); // Error: Whoops!
```
+<<<<<<< HEAD
...これは次のと同じように動作します:
```js run
@@ -76,10 +107,19 @@ new Promise(function(resolve, reject) {
}).then(function(result) {
*!*
throw new Error("Whoops!"); // promise を rejects
+=======
+...Works exactly the same as this:
+
+```js run
+new Promise((resolve, reject) => {
+*!*
+ reject(new Error("Whoops!"));
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}).catch(alert); // Error: Whoops!
```
+<<<<<<< HEAD
また、これは `throw` だけでなく同様にプログラムエラーを含む任意のエラーに対してです:
```js run
@@ -88,10 +128,37 @@ new Promise(function(resolve, reject) {
}).then(function(result) {
*!*
blabla(); // このような関数はありません
+=======
+The "invisible `try..catch`" around the executor automatically catches the error and turns it into rejected promise.
+
+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:
+
+```js run
+new Promise((resolve, reject) => {
+ resolve("ok");
+}).then((result) => {
+*!*
+ throw new Error("Whoops!"); // rejects the promise
+*/!*
+}).catch(alert); // Error: Whoops!
+```
+
+This happens for all errors, not just those caused by the `throw` statement. For example, a programming error:
+
+```js run
+new Promise((resolve, reject) => {
+ resolve("ok");
+}).then((result) => {
+*!*
+ blabla(); // no such function
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}).catch(alert); // ReferenceError: blabla is not defined
```
+<<<<<<< HEAD
最後の `.catch` は明示的な reject だけでなく、上記のハンドラのような偶発的なエラーもキャッチします。
## 再スロー
@@ -107,6 +174,23 @@ new Promise(function(resolve, reject) {
```js run
// 実行: catch -> then
new Promise(function(resolve, reject) {
+=======
+The final `.catch` not only catches explicit rejections, but also accidental errors in the handlers above.
+
+## Rethrowing
+
+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 it can't be handled. The same thing is possible for promises.
+
+If we `throw` inside `.catch`, then the control goes to the next closest error handler. And if we handle the error and finish normally, then it continues to the next closest successful `.then` handler.
+
+In the example below the `.catch` successfully handles the error:
+
+```js run
+// the execution: catch -> then
+new Promise((resolve, reject) => {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
throw new Error("Whoops!");
@@ -117,6 +201,7 @@ new Promise(function(resolve, reject) {
}).then(() => alert("Next successful handler runs"));
```
+<<<<<<< HEAD
ここでは、`.catch` ブロックが正常に終了しています。なので、次の成功 `.then` ハンドラが呼ばれます。
以下の例に、`.catch` の別のシチュエーションがあります。ハンドラ `(*)` はエラーをキャッチし、それが処理できない(例 `URIError` の処理の仕方しか知らない)ので、エラーを再びスローします:
@@ -124,31 +209,57 @@ new Promise(function(resolve, reject) {
```js run
// 実行: catch -> catch -> then
new Promise(function(resolve, reject) {
+=======
+Here the `.catch` block finishes normally. So the next successful `.then` handler is called.
+
+In the example below we see the other situation with `.catch`. The handler `(*)` catches the error and just can't handle it (e.g. it only knows how to handle `URIError`), so it throws it again:
+
+```js run
+// the execution: catch -> catch
+new Promise((resolve, reject) => {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
throw new Error("Whoops!");
}).catch(function(error) { // (*)
if (error instanceof URIError) {
+<<<<<<< HEAD
// エラー処理
+=======
+ // handle it
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
} else {
alert("Can't handle such error");
*!*
+<<<<<<< HEAD
throw error; // ここで投げられたエラーは次の catch へジャンプします
+=======
+ throw error; // throwing this or another error jumps to the next catch
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
}
}).then(function() {
+<<<<<<< HEAD
/* 実行されません */
}).catch(error => { // (**)
alert(`The unknown error has occurred: ${error}`);
// 何も返しません => 実行は通常通りに進みます
+=======
+ /* doesn't run here */
+}).catch(error => { // (**)
+
+ alert(`The unknown error has occurred: ${error}`);
+ // don't return anything => execution goes the normal way
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
});
```
+<<<<<<< HEAD
実行は最初の `.catch` `(*)` から、次の `.catch` `(**)` に移ります。
## 未処理の reject
@@ -173,18 +284,51 @@ new Promise(function() {
JavaScript エンジンはこのような reject を追跡し、その場合にはグローバルエラーを生成します。上の例を実行すると、コンソールでエラーを見ることができます。
ブラウザでは、イベント `unhandledrejection` を使ってキャッチできます。:
+=======
+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, we forgot to append `.catch` to the end of the chain, like here:
+
+```js untrusted run refresh
+new Promise(function() {
+ noSuchFunction(); // Error here (no such function)
+})
+ .then(() => {
+ // successful promise handlers, one or more
+ }); // without .catch at the end!
+```
+
+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 regular unhandled errors in code, it means that something has gone terribly wrong.
+
+What happens when a regular error occurs and is not caught by `try..catch`? The script dies with a message in the console. A 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.
+
+In the browser we can catch such errors using the event `unhandledrejection`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*
window.addEventListener('unhandledrejection', function(event) {
+<<<<<<< HEAD
// イベントオブジェクトは2つの特別なプロパティを持っています:
alert(event.promise); // [object Promise] - エラーを生成した promise
alert(event.reason); // Error: Whoops! - 未処理のエラーオブジェクト
+=======
+ // the event object has two special properties:
+ alert(event.promise); // [object Promise] - the promise that generated the error
+ alert(event.reason); // Error: Whoops! - the unhandled error object
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
});
*/!*
new Promise(function() {
throw new Error("Whoops!");
+<<<<<<< HEAD
}); // エラーを処理する catch がない
```
@@ -202,3 +346,23 @@ Node.jsのようなブラウザ以外の環境では、未処理のエラーを
- エラーを処理したい場所に正確に `.catch` を置き、それらを処理をする方法を知っておくべきです。ハンドラはエラーを分析(カスタムエラークラスが役立ちます)し、未知のものを再スローします。
- もしエラーから回復する方法がないのであれば、`.catch` をまったく使わなくてもOKです。
- いずれにせよ、"ただ落ちた" ということがないように、未知のエラーを追跡し、それをユーザ(とおそらく我々のサーバ)に知らせるために `unhandledrejection` イベントハンドラ(ブラウザの場合、他の環境の場合はその類似のもの)を持つべきです。
+=======
+}); // no catch to handle the error
+```
+
+The event is the part of the [HTML standard](https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections).
+
+If an error occurs, and there's no `.catch`, the `unhandledrejection` handler triggers, and gets the `event` object with the information about the error, so we can do something.
+
+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 ways to track unhandled errors.
+
+## Summary
+
+- `.catch` handles errors in promises of all kinds: be it a `reject()` call, or an error thrown in a handler.
+- `.then` also catches errors in the same manner, if given the second argument (which is the error 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 them, so that our app never "just dies".
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/05-promise-api/article.md b/1-js/11-async/05-promise-api/article.md
index abf602707c..3504b96194 100644
--- a/1-js/11-async/05-promise-api/article.md
+++ b/1-js/11-async/05-promise-api/article.md
@@ -1,5 +1,6 @@
# Promise API
+<<<<<<< HEAD
`Promise` クラスには 6 つの静的メソッドがあります。ここでそれらのユースケースについて簡単に説明します。
## Promise.all
@@ -11,11 +12,25 @@
これが `Promise.all` の目的です。
構文は次の通りです:
+=======
+There are 6 static methods in the `Promise` class. We'll quickly cover their use cases here.
+
+## Promise.all
+
+Let's say we want many promises to execute in parallel and wait until all of them are ready.
+
+For instance, download several URLs in parallel and process the content once they are all done.
+
+That's what `Promise.all` is for.
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let promise = Promise.all(iterable);
```
+<<<<<<< HEAD
`Promise.all` は iterable(反復可能, 通常は promise の配列)を取り、新しい promise を返します。
新しい promise は、配列の各 promise がすべて解決され、それらの結果を配列に持つと解決(resolve)されます。
@@ -35,6 +50,27 @@ Promise.all([
一般的なやり方は、処理データの配列を promise の配列にマップし、それを `Promise.all` にラップすることです。
例えば、URL の配列がある場合、次のようにしてすべてをフェッチできます:
+=======
+`Promise.all` takes an iterable (usually, an array of promises) and returns a new promise.
+
+The new promise resolves when all listed promises are resolved, 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]`:
+
+```js run
+Promise.all([
+ new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
+ new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
+ new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
+]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member
+```
+
+Please note that the order of the resulting array members is the same as in its 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`.
+
+For instance, if we have an array of URLs, we can fetch them all like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let urls = [
@@ -43,17 +79,28 @@ let urls = [
'https://api.github.com/users/jeresig'
];
+<<<<<<< HEAD
// 各 url を promise の fetch(github url) へマップする
let requests = urls.map(url => fetch(url));
// Promise.all はすべてのジョブが解決されるまで待ちます
+=======
+// map every url to the promise of the fetch
+let requests = urls.map(url => fetch(url));
+
+// Promise.all waits until all jobs are resolved
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
Promise.all(requests)
.then(responses => responses.forEach(
response => alert(`${response.url}: ${response.status}`)
));
```
+<<<<<<< HEAD
名前からGithubユーザのユーザ情報を取得するより大きな例です(id で商品の配列をフェッチできますが、ロジックは同じです):
+=======
+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 identical):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let names = ['iliakan', 'remy', 'jeresig'];
@@ -62,13 +109,20 @@ let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
Promise.all(requests)
.then(responses => {
+<<<<<<< HEAD
// すべてのレスポンスが用意できたら HTTP ステータスコードが見られます
for(let response of responses) {
alert(`${response.url}: ${response.status}`); // 各 url で 200 が表示されます
+=======
+ // all responses are resolved successfully
+ for(let response of responses) {
+ alert(`${response.url}: ${response.status}`); // shows 200 for every url
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
return responses;
})
+<<<<<<< HEAD
// それぞれの中身を読むために、レスポンスの配列を response.json() の配列にマッピングします
.then(responses => Promise.all(responses.map(r => r.json())))
// すべての JSON応答が解析され、"user" はそれらの配列です。
@@ -78,6 +132,17 @@ Promise.all(requests)
**いずれかの promise が reject された場合、`Promise.all` により返却された promise は即座にエラーと一緒に reject します。**
例:
+=======
+ // map array of responses into an array of response.json() to read their content
+ .then(responses => Promise.all(responses.map(r => r.json())))
+ // all JSON answers are parsed: "users" is the array of them
+ .then(users => users.forEach(user => alert(user.name)));
+```
+
+**If any of the promises is rejected, the promise returned by `Promise.all` immediately rejects with that error.**
+
+For instance:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.all([
@@ -89,6 +154,7 @@ Promise.all([
]).catch(alert); // Error: Whoops!
```
+<<<<<<< HEAD
ここでは、2つ目の promise が2秒後に reject されます。それは即座に `Promise.all` の reject に繋がるため、`catch` が実行されます。: reject されたエラーは `Promise.all` 全体の結果になります。
```warn header="エラー時の場合, 他の promise は無視されます"
@@ -103,31 +169,61 @@ Promise.all([
通常、`Promise.all(iterable)` は promise の iterable (ほとんどの場合は配列)を受け付けます。しかし、もしそれらのオブジェクトが promise ではない場合、`Promise.resolve` でラップします。
例えば、ここでは結果は `[1, 2, 3]` になります:
+=======
+Here the second promise rejects in two seconds. That leads to an immediate rejection of `Promise.all`, so `.catch` executes: the rejection error becomes the outcome of the entire `Promise.all`.
+
+```warn header="In case of an error, other promises are ignored"
+If one promise rejects, `Promise.all` immediately rejects, completely forgetting about the other ones in the list. Their results are ignored.
+
+For example, if there are multiple `fetch` calls, like in the example above, and one fails, the others will still continue to execute, but `Promise.all` won't watch them anymore. They will probably settle, but their results will be ignored.
+
+`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(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]`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000)
}),
+<<<<<<< HEAD
2, // Promise.resolve(2) と扱われる
3 // Promise.resolve(3) と扱われる
]).then(alert); // 1, 2, 3
```
したがって、必要に応じて準備済みの値を `Promise.all` に渡せます。
+=======
+ 2,
+ 3
+]).then(alert); // 1, 2, 3
+```
+
+So we are able to pass ready values to `Promise.all` where convenient.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
````
## Promise.allSettled
[recent browser="new"]
+<<<<<<< HEAD
`Promise.all` はいずれかの promise が reject されると、全体として reject されます。これは "白か黒か" のケースにはよいです。続行するために *すべての* 成功した結果が必要な場合です:
+=======
+`Promise.all` rejects as a whole if any promise rejects. That's good for "all or nothing" cases, when we need *all* results successful to proceed:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
Promise.all([
fetch('/template.html'),
fetch('/style.css'),
fetch('/data.json')
+<<<<<<< HEAD
]).then(render); // render メソッドはすべての fetch の結果が必要
```
@@ -139,6 +235,19 @@ Promise.all([
例えば、複数のユーザに対する情報をフェッチしたいとします。たとえ1リクエストが失敗しても、他の結果はほしいです。
`Promise.allSettled` を使いましょう:
+=======
+]).then(render); // render method needs results of all fetches
+```
+
+`Promise.allSettled` just waits for all promises to settle, regardless of the result. 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 still interested in the others.
+
+Let's use `Promise.allSettled`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let urls = [
@@ -160,6 +269,7 @@ Promise.allSettled(urls.map(url => fetch(url)))
});
```
+<<<<<<< HEAD
上の行 `(*)` の `results` は以下になります:
```js
[
@@ -174,6 +284,22 @@ Promise.allSettled(urls.map(url => fetch(url)))
### Polyfill
ブラウザでは、`Promise.allSettled` をサポートしていません。が polyfill するのは簡単です:
+=======
+The `results` in the line `(*)` above will be:
+```js
+[
+ {status: 'fulfilled', value: ...response...},
+ {status: 'fulfilled', value: ...response...},
+ {status: 'rejected', reason: ...error object...}
+]
+```
+
+So for each promise we get its status and `value/error`.
+
+### Polyfill
+
+If the browser doesn't support `Promise.allSettled`, it's easy to polyfill:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (!Promise.allSettled) {
@@ -188,6 +314,7 @@ if (!Promise.allSettled) {
}
```
+<<<<<<< HEAD
このコードで、`promises.map` は入力値を取り、`p => Promise.resolve(p)` でそれらを promise に変換(非 promise が渡された場合に備えて)し、`.then` ハンドラに追加します。
ハンドラは成功した結果 `value` を `{status:'fulfilled', value}` に、エラー `reason` は `{status:'rejected', reason}` に変換します。これは `Promise.allSettled` のフォーマットです。
@@ -199,12 +326,29 @@ if (!Promise.allSettled) {
これは `Promise.all` と同様ですが、すべてが完了するのを待つのではなく、最初の結果(またはエラー)のみを待ちます。
構文です:
+=======
+In this code, `promises.map` takes input values, turns them 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 `value` into `{status:'fulfilled', value}`, and an error `reason` into `{status:'rejected', reason}`. That's exactly the format of `Promise.allSettled`.
+
+Now we can use `Promise.allSettled` to get the results of *all* given promises, even if some of them reject.
+
+## Promise.race
+
+Similar to `Promise.all`, but waits only for the first settled promise and gets its result (or error).
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let promise = Promise.race(iterable);
```
+<<<<<<< HEAD
例えば、ここでは結果は `1` になります:
+=======
+For instance, here the result will be `1`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.race([
@@ -214,20 +358,34 @@ Promise.race([
]).then(alert); // 1
```
+<<<<<<< HEAD
なので、最初の結果/エラーが `Promise.race` 全体の結果になります。最初の確定した promise が "レースに勝った" 後、それ以外の結果/エラーは無視されます。
+=======
+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.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
## Promise.any
+<<<<<<< HEAD
`Promise.race` と同様ですが、最初の履行した(fulfilled) promise のみを待ち、その結果を得ます。指定された promise がすべて reject された場合、返却された promise は [`AggregateError`](mdn:js/AggregateError) で reject されます(`errors` プロパティにすべての promise エラーを格納する特別なエラーオブジェクトです)。
構文は次の通りです:
+=======
+Similar to `Promise.race`, but waits only for the first fulfilled promise and gets its result. If all of the given promises are rejected, then the returned promise is rejected with [`AggregateError`](mdn:js/AggregateError) - a special error object that stores all promise errors in its `errors` property.
+
+The syntax is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let promise = Promise.any(iterable);
```
+<<<<<<< HEAD
例えば、ここでは結果は `1` になります:
+=======
+For instance, here the result will be `1`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.any([
@@ -237,9 +395,15 @@ Promise.any([
]).then(alert); // 1
```
+<<<<<<< HEAD
最初の promise が一番はやいですが、reject されたため、2つ目の promise が結果になっています。最初の履行した(fulfilled)promise が "レースに勝ち"、他の結果はすべて無視されます。
これは promise がすべて失敗した例です:
+=======
+The first promise here was fastest, but it was rejected, so the second promise became the result. After the first fulfilled promise "wins the race", all further results are ignored.
+
+Here's an example when all promises fail:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.any([
@@ -252,6 +416,7 @@ Promise.any([
});
```
+<<<<<<< HEAD
ご覧の通り、失敗した promise のエラーオブジェクトは `AggregateError` オブジェクトの `errors` プロパティで利用可能です。
## Promise.resolve/reject
@@ -265,14 +430,35 @@ Promise.any([
`Promise.resolve(value)` は結果 `value` をもつ解決された promise を作成します。
以下と同様です:
+=======
+As you can see, error objects for failed promises are available in the `errors` property of the `AggregateError` object.
+
+## Promise.resolve/reject
+
+Methods `Promise.resolve` and `Promise.reject` are rarely needed in modern code, because `async/await` syntax (we'll cover it [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
+
+`Promise.resolve(value)` creates a resolved promise with the result `value`.
+
+Same as:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let promise = new Promise(resolve => resolve(value));
```
+<<<<<<< HEAD
このメソッドは、関数が promise を返すことが期待される場合の互換性のために使用されます。
例えば、以下の `loadCached` 関数は、URL をフェッチし、コンテンツを記憶(キャッシュ)します。同じURLに対する将来の呼び出し時には、キャッシュから即座にコンテンツが返されますが、promise にするために `Promise.resolve` を使用します。これで戻り値は常に promise になります:
+=======
+The method is used for compatibility, when a function is expected to return a promise.
+
+For example, the `loadCached` function below fetches a 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 the returned value is always a promise:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let cache = new Map();
@@ -293,6 +479,7 @@ function loadCached(url) {
}
```
+<<<<<<< HEAD
関数は promise を返すことが保証されているため、`loadCached(url).then(…)` と書くことができます。`loadCached` の後に常に `.then` が使用でき、これが行 `(*)` の `Promise.resolve` の目的です。
### Promise.reject
@@ -300,11 +487,21 @@ function loadCached(url) {
`Promise.reject(error)` は `error` を持つ reject された promise を作成します。
以下と同じです:
+=======
+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:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let promise = new Promise((resolve, reject) => reject(error));
```
+<<<<<<< HEAD
実際、このメソッドはほとんど使われません。
## サマリ
@@ -321,3 +518,21 @@ let promise = new Promise((resolve, reject) => reject(error));
6. `Promise.reject(error)` -- 与えられたエラーで promise を拒否(reject)します
これらのうち、`Promise.all` が実践では最も一般的です。
+=======
+In practice, this method is almost never used.
+
+## Summary
+
+There are 6 static methods of `Promise` class:
+
+1. `Promise.all(promises)` -- waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, 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 an array of objects with:
+ - `status`: `"fulfilled"` or `"rejected"`
+ - `value` (if fulfilled) or `reason` (if rejected).
+3. `Promise.race(promises)` -- waits for the first promise to settle, and its result/error becomes the outcome.
+4. `Promise.any(promises)` (recently added method) -- waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, [`AggregateError`](mdn:js/AggregateError) becomes the error of `Promise.any`.
+5. `Promise.resolve(value)` -- makes a resolved promise with the given value.
+6. `Promise.reject(error)` -- makes a rejected promise with the given error.
+
+Of all these, `Promise.all` is probably the most common in practice.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/06-promisify/article.md b/1-js/11-async/06-promisify/article.md
index 415f476231..d95c107155 100644
--- a/1-js/11-async/06-promisify/article.md
+++ b/1-js/11-async/06-promisify/article.md
@@ -1,5 +1,6 @@
# Promisification
+<<<<<<< HEAD
"Promisification" は単純な変換を表す長い用語です。コールバックを受け付ける関数から、Promise を返す関数への変換です。
多くの関数やライブラリはコールバックベースなので、このような変換は実際しばしば必要とされます。Promise はより便利であるため、このような変換は理にかなっています。
@@ -7,6 +8,15 @@
より理解するために例を見てみましょう。
例えば、章 の `loadScript(src, callback)` を考えてみましょう。
+=======
+"Promisification" is a long word for a simple transformation. It's the conversion of a function that accepts a callback into a function that returns a promise.
+
+Such transformations are often required in real-life, as many functions and libraries are callback-based. But promises are more convenient, so it makes sense to promisify them.
+
+For better understanding, let's see an example.
+
+For instance, we have `loadScript(src, callback)` from the chapter .
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function loadScript(src, callback) {
@@ -19,6 +29,7 @@ function loadScript(src, callback) {
document.head.append(script);
}
+<<<<<<< HEAD
// 使用例:
// loadScript('path/script.js', (err, script) => {...})
```
@@ -32,10 +43,26 @@ Promise 化してみましょう。
つまり、`src` のみ(`callback` なし)を渡し、戻り値で promise を得ます。この promise は読み込みが成功すると `script` で resolve し、そうでなければエラーで reject します。
こちらです:
+=======
+// usage:
+// loadScript('path/script.js', (err, script) => {...})
+```
+
+The function loads a script with the given `src`, and then calls `callback(err)` in case of an error, or `callback(null, script)` in case of successful loading. That's a widespread agreement for using callbacks, we saw it before.
+
+Let's promisify it.
+
+We'll make a new function `loadScriptPromise(src)`, that does the same (loads the script), but returns a promise instead of using callbacks.
+
+In other words, we pass it only `src` (no `callback`) and get a promise in return, that resolves with `script` when the load is successful, and rejects with the error otherwise.
+
+Here it is:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let loadScriptPromise = function(src) {
return new Promise((resolve, reject) => {
loadScript(src, (err, script) => {
+<<<<<<< HEAD
if (err) reject(err)
else resolve(script);
});
@@ -61,11 +88,39 @@ function promisify(f) {
function callback(err, result) { // f のためのカスタムコールバック
if (err) {
return reject(err);
+=======
+ if (err) reject(err);
+ else resolve(script);
+ });
+ });
+};
+
+// usage:
+// loadScriptPromise('path/script.js').then(...)
+```
+
+As we can see, the new function is a wrapper around the original `loadScript` function. It calls it providing its own callback that translates to promise `resolve/reject`.
+
+Now `loadScriptPromise` fits well in promise-based code. If we like promises more than callbacks (and soon we'll see more reasons for that), then we will use it instead.
+
+In practice we may need to promisify more than one function, so it makes sense to use a helper.
+
+We'll call it `promisify(f)`: it accepts a to-promisify function `f` and returns a wrapper function.
+
+```js
+function promisify(f) {
+ return function (...args) { // return a wrapper-function (*)
+ return new Promise((resolve, reject) => {
+ function callback(err, result) { // our custom callback for f (**)
+ if (err) {
+ reject(err);
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
} else {
resolve(result);
}
}
+<<<<<<< HEAD
args.push(callback); // 引数の末尾にカスタムコールバックを追加
f.call(this, ...args); // 元の関数を呼び出します
@@ -74,10 +129,21 @@ function promisify(f) {
};
// 使用例:
+=======
+ args.push(callback); // append our custom callback to the end of f arguments
+
+ f.call(this, ...args); // call the original function
+ });
+ };
+}
+
+// usage:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let loadScriptPromise = promisify(loadScript);
loadScriptPromise(...).then(...);
```
+<<<<<<< HEAD
コードは多少複雑に見えますが、`loadScript` 関数の Promise 化をしており、本質的には上で書いたものと同じです。
`promisify(f)` の呼び出しは、`f` `(*)` のラッパーを返します。ラッパーは promise を返し、呼び出しを元の `f` に転送し、カスタムコールバック `(**)` で結果を追跡します。
@@ -101,6 +167,31 @@ function promisify(f, manyArgs = false) {
return reject(err);
} else {
// manyArgs が指定されている場合、すべてのコールバック結果で resolve します
+=======
+The code may look a bit complex, but it's essentially the same that we wrote above, while promisifying `loadScript` function.
+
+A call to `promisify(f)` returns a wrapper around `f` `(*)`. That wrapper returns a promise and forwards the call to the original `f`, tracking the result in the custom callback `(**)`.
+
+Here, `promisify` assumes that the original function expects a callback with exactly 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, ...)`?
+
+We can improve our helper. Let's make a more advanced version of `promisify`.
+
+- When called as `promisify(f)` it should work similar to the version above.
+- When called as `promisify(f, true)`, it should return the promise that resolves with the array of callback results. That's exactly for callbacks with many arguments.
+
+```js
+// promisify(f, true) to get array of results
+function promisify(f, manyArgs = false) {
+ return function (...args) {
+ return new Promise((resolve, reject) => {
+ function *!*callback(err, ...results*/!*) { // our custom callback for f
+ if (err) {
+ reject(err);
+ } else {
+ // resolve with all callback results if manyArgs is specified
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*resolve(manyArgs ? results : results[0]);*/!*
}
}
@@ -110,6 +201,7 @@ function promisify(f, manyArgs = false) {
f.call(this, ...args);
});
};
+<<<<<<< HEAD
};
// 使用例:
@@ -129,4 +221,25 @@ Promisification は素晴らしいアプローチです。特に `async/await` (
覚えておいてください、Promise は1つの結果のみを持ちますが、コールバックは技術的には何度も呼ぶことができます。
そのため、Promisification はコールバックを1度だけ呼ぶ関数のみを対象としています。それ以降の呼び出しは無視されます。
+=======
+}
+
+// usage:
+f = promisify(f, true);
+f(...).then(arrayOfResults => ..., err => ...);
+```
+
+As you can see it's essentially the same as above, but `resolve` is called with only one or all arguments depending on whether `manyArgs` is truthy.
+
+For more exotic callback formats, like those without `err` at all: `callback(result)`, we can promisify such functions manually without using the helper.
+
+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.
+
+```smart
+Promisification is a great approach, especially when you use `async/await` (covered later in the chapter ), but not a total replacement for callbacks.
+
+Remember, a promise may have only one result, but a callback may technically be called many times.
+
+So promisification is only meant for functions that call the callback once. Further calls will be ignored.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
diff --git a/1-js/11-async/07-microtask-queue/article.md b/1-js/11-async/07-microtask-queue/article.md
index 1459076975..3cf6ff5ed5 100644
--- a/1-js/11-async/07-microtask-queue/article.md
+++ b/1-js/11-async/07-microtask-queue/article.md
@@ -1,17 +1,26 @@
# Microtasks
+<<<<<<< HEAD
Promise ハンドラ `.then`/`.catch`/`.finally` は常に非同期です。
たとえ Promise がすくに解決されたとしても、`.then`/`.catch`/`.finally` の *下* にあるコードはこれらのハンドラの前に実行されます。
デモです:
+=======
+Promise handlers `.then`/`.catch`/`.finally` are always asynchronous.
+
+Even when a Promise is immediately resolved, the code on the lines *below* `.then`/`.catch`/`.finally` will still execute before these handlers.
+
+Here's a demo:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let promise = Promise.resolve();
promise.then(() => alert("promise done!"));
+<<<<<<< HEAD
alert("code finished"); // このアラートが最初に表示されます
```
@@ -43,6 +52,39 @@ Promise ハンドラは常に内部キューを通ります。
**順序が重要な場合はどうなるでしょうか? `promise done` の後に `code finished` を処理したい場合はどうすればよいでしょう?**
簡単です、単に `.then` でキューに入れるだけです:
+=======
+alert("code finished"); // this alert shows first
+```
+
+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 queue
+
+Asynchronous tasks need proper management. For that, the ECMA standard specifies an internal queue `PromiseJobs`, more often referred to as the "microtask queue" (V8 term).
+
+As stated in the [specification](https://tc39.github.io/ecma262/#sec-jobs-and-job-queues):
+
+- The queue is first-in-first-out: tasks enqueued first are run first.
+- Execution of a task is initiated only when nothing else is running.
+
+Or, to put it more simply, when a promise is ready, its `.then/catch/finally` handlers are put into the queue; they are not executed yet. When the JavaScript engine becomes free from the current code, it takes a task from the queue and executes it.
+
+That's why "code finished" in the example above shows first.
+
+
+
+Promise handlers always go through this internal queue.
+
+If there's a chain with multiple `.then/catch/finally`, then every one of them is executed asynchronously. That is, it first gets queued, then executed when the current code is complete and previously queued handlers are finished.
+
+**What if the order matters for us? How can we make `code finished` appear after `promise done`?**
+
+Easy, just put it into the queue with `.then`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
Promise.resolve()
@@ -50,6 +92,7 @@ Promise.resolve()
.then(() => alert("code finished"));
```
+<<<<<<< HEAD
これで順番は期待通りです。
## 未処理の拒否(Unhandled rejection)
@@ -61,6 +104,19 @@ Promise.resolve()
**"未処理の拒否" は、microtask キューの最後で Promise エラーが処理されない場合に発生します。**
通常、エラーが予想される場合には、それを処理するために Promise チェーンに `.catch` を追加します:
+=======
+Now the order is as intended.
+
+## Unhandled rejection
+
+Remember the `unhandledrejection` event from the article ?
+
+Now we can see exactly how JavaScript finds out that there was an unhandled rejection.
+
+**An "unhandled rejection" occurs when a promise error is not handled at the end of the microtask queue.**
+
+Normally, if we expect an error, we add `.catch` to the promise chain to handle it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let promise = Promise.reject(new Error("Promise Failed!"));
@@ -68,20 +124,36 @@ let promise = Promise.reject(new Error("Promise Failed!"));
promise.catch(err => alert('caught'));
*/!*
+<<<<<<< HEAD
// 実行されません: error handled
window.addEventListener('unhandledrejection', event => alert(event.reason));
```
...ですが、`.catch` を忘れていた場合、microtask キューが空になった後、エンジンはイベントをトリガーします:
+=======
+// doesn't run: error handled
+window.addEventListener('unhandledrejection', event => alert(event.reason));
+```
+
+But if we forget to add `.catch`, then, after the microtask queue is empty, the engine triggers the event:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let promise = Promise.reject(new Error("Promise Failed!"));
+<<<<<<< HEAD
// 実行されます: Promise Failed!
window.addEventListener('unhandledrejection', event => alert(event.reason));
```
仮に、次のように後でエラーを処理するとどうなるでしょう?:
+=======
+// Promise Failed!
+window.addEventListener('unhandledrejection', event => alert(event.reason));
+```
+
+What if we handle the error later? Like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let promise = Promise.reject(new Error("Promise Failed!"));
@@ -89,6 +161,7 @@ let promise = Promise.reject(new Error("Promise Failed!"));
setTimeout(() => promise.catch(err => alert('caught')), 1000);
*/!*
+<<<<<<< HEAD
// 実行されます: Error: Promise Failed!
window.addEventListener('unhandledrejection', event => alert(event.reason));
```
@@ -110,3 +183,26 @@ microtask キューについて知らなければ、不思議に思うでしょ
あるコードが `.then/catch/finally` の後に実行されることを保証する必要がある場合、Promise チェーンを使い `.then` で呼び出します
ブラウザも Node.js も含めほとんどの JavaScript エンジンでは、microtask の概念は "イベントループ" と "microtask" と密接に関連しています。これらは Promise とは直接は関係ないので、チュートリアルの別のパート、チャプター で説明しています。
+=======
+// Error: Promise Failed!
+window.addEventListener('unhandledrejection', event => alert(event.reason));
+```
+
+Now, if we run it, we'll see `Promise Failed!` first and then `caught`.
+
+If we didn't know about the microtasks queue, we could wonder: "Why did `unhandledrejection` handler run? We did catch and handle the error!"
+
+But now we understand that `unhandledrejection` is generated when the microtask queue is complete: the engine examines promises and, if any of them is in the "rejected" state, then the event triggers.
+
+In the example above, `.catch` added by `setTimeout` also triggers. But it does so later, after `unhandledrejection` has already occurred, so it doesn't change anything.
+
+## Summary
+
+Promise handling is always asynchronous, as all promise actions pass through the internal "promise jobs" queue, also called "microtask queue" (V8 term).
+
+So `.then/catch/finally` handlers are always called after the current code is finished.
+
+If we need to guarantee that a piece of code is executed after `.then/catch/finally`, we can add it into a chained `.then` call.
+
+In most Javascript engines, including browsers and Node.js, the concept of microtasks is closely tied with the "event loop" and "macrotasks". As these have no direct relation to promises, they are covered in another part of the tutorial, in the article .
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/08-async-await/01-rewrite-async/solution.md b/1-js/11-async/08-async-await/01-rewrite-async/solution.md
index 4daab2935c..0ff66720ec 100644
--- a/1-js/11-async/08-async-await/01-rewrite-async/solution.md
+++ b/1-js/11-async/08-async-await/01-rewrite-async/solution.md
@@ -1,5 +1,9 @@
+<<<<<<< HEAD
補足はコードの下にあります:
+=======
+The notes are below the code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function loadJson(url) { // (1)
@@ -13,6 +17,7 @@ async function loadJson(url) { // (1)
throw new Error(response.status);
}
+<<<<<<< HEAD
loadJson('no-such-user.json')
.catch(alert); // Error: 404 (4)
```
@@ -22,6 +27,17 @@ loadJson('no-such-user.json')
1. 関数 `loadJson` は `async` になります。
2. すべての内側の `.then` は `await` に置き換えられます。
3. 次のように、await するのではなく、`response.json()` を返すこともできます。:
+=======
+loadJson('https://javascript.info/no-such-user.json')
+ .catch(alert); // Error: 404 (4)
+```
+
+Notes:
+
+1. The function `loadJson` becomes `async`.
+2. All `.then` inside are replaced with `await`.
+3. We can `return response.json()` instead of awaiting for it, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
if (response.status == 200) {
@@ -29,5 +45,10 @@ loadJson('no-such-user.json')
}
```
+<<<<<<< HEAD
そうすると、外側のコードはその promise を解決するために `await` する必要があります。
4. `loadJson` からスローされたエラーは `.catch` で処理されます。そこでは `await loadJson(…)` を使うことができません。なぜなら `async` 関数の中ではないからです。
+=======
+ Then the outer code would have to `await` for that promise to resolve. In our case it doesn't matter.
+4. The error thrown from `loadJson` is handled by `.catch`. We can't use `await loadJson(…)` there, because we're not in an `async` function.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/08-async-await/01-rewrite-async/task.md b/1-js/11-async/08-async-await/01-rewrite-async/task.md
index 00cdc2052a..2def765fd2 100644
--- a/1-js/11-async/08-async-await/01-rewrite-async/task.md
+++ b/1-js/11-async/08-async-await/01-rewrite-async/task.md
@@ -1,7 +1,11 @@
# async/await を使用して書き直す
+<<<<<<< HEAD
チャプター にある例の1つを `.then/catch` の代わりに `async/await` を使って書き直してください。:
+=======
+Rewrite this example code from the chapter using `async/await` instead of `.then/catch`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function loadJson(url) {
@@ -12,9 +16,9 @@ function loadJson(url) {
} else {
throw new Error(response.status);
}
- })
+ });
}
-loadJson('no-such-user.json') // (3)
+loadJson('https://javascript.info/no-such-user.json')
.catch(alert); // Error: 404
```
diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
index 9293bcf6c9..52443f3092 100644
--- a/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
+++ b/1-js/11-async/08-async-await/02-rewrite-async-2/solution.md
@@ -1,5 +1,9 @@
+<<<<<<< HEAD
ここには細工はありません。単に `demoGithubUser` の中の `.catch` を `try...catch` に置き換え、必要な場所に `async/await` を追加しています:
+=======
+There are no tricks here. Just replace `.catch` with `try..catch` inside `demoGithubUser` and add `async/await` where needed:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class HttpError extends Error {
diff --git a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md
index 7870cf7034..a3e638612a 100644
--- a/1-js/11-async/08-async-await/02-rewrite-async-2/task.md
+++ b/1-js/11-async/08-async-await/02-rewrite-async-2/task.md
@@ -1,7 +1,13 @@
+<<<<<<< HEAD
# "再スロー" を async/await で書き直す
下にチャプター にある "再スロー" の例があります。`.then/catch` の代わりに `async/await` を使って書き直してください。
+=======
+# Rewrite "rethrow" with async/await
+
+Below you can find the "rethrow" example. Rewrite it using `async/await` instead of `.then/catch`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
また、`demoGithubUser` のループのために(`async/await` が簡単になるよう)再帰を取り除きます。
@@ -22,7 +28,7 @@ function loadJson(url) {
} else {
throw new HttpError(response);
}
- })
+ });
}
// gitub が有効なユーザを返すまでユーザ名を訪ねる
diff --git a/1-js/11-async/08-async-await/03-async-from-regular/solution.md b/1-js/11-async/08-async-await/03-async-from-regular/solution.md
index f551356ca6..af742f1195 100644
--- a/1-js/11-async/08-async-await/03-async-from-regular/solution.md
+++ b/1-js/11-async/08-async-await/03-async-from-regular/solution.md
@@ -1,7 +1,13 @@
+<<<<<<< HEAD
`async` 呼び出しを Promise として扱い、それに `.then` をつけるだけです。
+=======
+That's the case when knowing how it works inside is helpful.
+
+Just treat `async` call as promise and attach `.then` to it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function wait() {
await new Promise(resolve => setTimeout(resolve, 1000));
@@ -10,7 +16,11 @@ async function wait() {
}
function f() {
+<<<<<<< HEAD
// 1秒後に 10を表示
+=======
+ // shows 10 after 1 second
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
wait().then(result => alert(result));
*/!*
diff --git a/1-js/11-async/08-async-await/03-async-from-regular/task.md b/1-js/11-async/08-async-await/03-async-from-regular/task.md
index 8991fc723c..09a74b7eb6 100644
--- a/1-js/11-async/08-async-await/03-async-from-regular/task.md
+++ b/1-js/11-async/08-async-await/03-async-from-regular/task.md
@@ -1,7 +1,13 @@
+<<<<<<< HEAD
# 非 async から async を呼び出す
"通常" の関数があります。そこから `async` 呼び出しを行い、その結果を使うにはどうすればよいでしょう?
+=======
+# Call async from non-async
+
+We have a "regular" function called `f`. How can you call the `async` function `wait()` and use its result inside of `f`?
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
async function wait() {
@@ -11,6 +17,7 @@ async function wait() {
}
function f() {
+<<<<<<< HEAD
// ...ここに何を書きますか?
// async wait() をして 10 を取得するのを待ちます
// 覚えておいてください、"await" は使えません
@@ -18,3 +25,12 @@ function f() {
```
P.S. このタスクは技術的には非常に単純です。が、async/await に不慣れた開発者によくある質問です。
+=======
+ // ...what should you write here?
+ // we need to call async wait() and wait to get 10
+ // remember, we can't use "await"
+}
+```
+
+P.S. The task is technically very simple, but the question is quite common for developers new to async/await.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/08-async-await/04-promise-all-failure/solution.md b/1-js/11-async/08-async-await/04-promise-all-failure/solution.md
new file mode 100644
index 0000000000..9fda8e000f
--- /dev/null
+++ b/1-js/11-async/08-async-await/04-promise-all-failure/solution.md
@@ -0,0 +1,113 @@
+
+The root of the problem is that `Promise.all` immediately rejects when one of its promises rejects, but it do nothing to cancel the other promises.
+
+In our case, the second query fails, so `Promise.all` rejects, and the `try...catch` block catches this error.Meanwhile, other promises are *not affected* - they independently continue their execution. In our case, the third query throws an error of its own after a bit of time. And that error is never caught, we can see it in the console.
+
+The problem is especially dangerous in server-side environments, such as Node.js, when an uncaught error may cause the process to crash.
+
+How to fix it?
+
+An ideal solution would be to cancel all unfinished queries when one of them fails. This way we avoid any potential errors.
+
+However, the bad news is that service calls (such as `database.query`) are often implemented by a 3rd-party library which doesn't support cancellation. Then there's no way to cancel a call.
+
+As an alternative, we can write our own wrapper function around `Promise.all` which adds a custom `then/catch` handler to each promise to track them: results are gathered and, if an error occurs, all subsequent promises are ignored.
+
+```js
+function customPromiseAll(promises) {
+ return new Promise((resolve, reject) => {
+ const results = [];
+ let resultsCount = 0;
+ let hasError = false; // we'll set it to true upon first error
+
+ promises.forEach((promise, index) => {
+ promise
+ .then(result => {
+ if (hasError) return; // ignore the promise if already errored
+ results[index] = result;
+ resultsCount++;
+ if (resultsCount === promises.length) {
+ resolve(results); // when all results are ready - successs
+ }
+ })
+ .catch(error => {
+ if (hasError) return; // ignore the promise if already errored
+ hasError = true; // wops, error!
+ reject(error); // fail with rejection
+ });
+ });
+ });
+}
+```
+
+This approach has an issue of its own - it's often undesirable to `disconnect()` when queries are still in the process.
+
+It may be important that all queries complete, especially if some of them make important updates.
+
+So we should wait until all promises are settled before going further with the execution and eventually disconnecting.
+
+Here's another implementation. It behaves similar to `Promise.all` - also resolves with the first error, but waits until all promises are settled.
+
+```js
+function customPromiseAllWait(promises) {
+ return new Promise((resolve, reject) => {
+ const results = new Array(promises.length);
+ let settledCount = 0;
+ let firstError = null;
+
+ promises.forEach((promise, index) => {
+ Promise.resolve(promise)
+ .then(result => {
+ results[index] = result;
+ })
+ .catch(error => {
+ if (firstError === null) {
+ firstError = error;
+ }
+ })
+ .finally(() => {
+ settledCount++;
+ if (settledCount === promises.length) {
+ if (firstError !== null) {
+ reject(firstError);
+ } else {
+ resolve(results);
+ }
+ }
+ });
+ });
+ });
+}
+```
+
+Now `await customPromiseAllWait(...)` will stall the execution until all queries are processed.
+
+This is a more reliable approach, as it guarantees a predictable execution flow.
+
+Lastly, if we'd like to process all errors, we can use either use `Promise.allSettled` or write a wrapper around it to gathers all errors in a single [AggregateError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError) object and rejects with it.
+
+```js
+// wait for all promises to settle
+// return results if no errors
+// throw AggregateError with all errors if any
+function allOrAggregateError(promises) {
+ return Promise.allSettled(promises).then(results => {
+ const errors = [];
+ const values = [];
+
+ results.forEach((res, i) => {
+ if (res.status === 'fulfilled') {
+ values[i] = res.value;
+ } else {
+ errors.push(res.reason);
+ }
+ });
+
+ if (errors.length > 0) {
+ throw new AggregateError(errors, 'One or more promises failed');
+ }
+
+ return values;
+ });
+}
+```
diff --git a/1-js/11-async/08-async-await/04-promise-all-failure/task.md b/1-js/11-async/08-async-await/04-promise-all-failure/task.md
new file mode 100644
index 0000000000..74571c43e3
--- /dev/null
+++ b/1-js/11-async/08-async-await/04-promise-all-failure/task.md
@@ -0,0 +1,79 @@
+
+# Dangerous Promise.all
+
+`Promise.all` is a great way to parallelize multiple operations. It's especially useful when we need to make parallel requests to multiple services.
+
+However, there's a hidden danger. We'll see an example in this task and explore how to avoid it.
+
+Let's say we have a connection to a remote service, such as a database.
+
+There're two functions: `connect()` and `disconnect()`.
+
+When connected, we can send requests using `database.query(...)` - an async function which usually returns the result but also may throw an error.
+
+Here's a simple implementation:
+
+```js
+let database;
+
+function connect() {
+ database = {
+ async query(isOk) {
+ if (!isOk) throw new Error('Query failed');
+ }
+ };
+}
+
+function disconnect() {
+ database = null;
+}
+
+// intended usage:
+// connect()
+// ...
+// database.query(true) to emulate a successful call
+// database.query(false) to emulate a failed call
+// ...
+// disconnect()
+```
+
+Now here's the problem.
+
+We wrote the code to connect and send 3 queries in parallel (all of them take different time, e.g. 100, 200 and 300ms), then disconnect:
+
+```js
+// Helper function to call async function `fn` after `ms` milliseconds
+function delay(fn, ms) {
+ return new Promise((resolve, reject) => {
+ setTimeout(() => fn().then(resolve, reject), ms);
+ });
+}
+
+async function run() {
+ connect();
+
+ try {
+ await Promise.all([
+ // these 3 parallel jobs take different time: 100, 200 and 300 ms
+ // we use the `delay` helper to achieve this effect
+*!*
+ delay(() => database.query(true), 100),
+ delay(() => database.query(false), 200),
+ delay(() => database.query(false), 300)
+*/!*
+ ]);
+ } catch(error) {
+ console.log('Error handled (or was it?)');
+ }
+
+ disconnect();
+}
+
+run();
+```
+
+Two of these queries happen to be unsuccessful, but we're smart enough to wrap the `Promise.all` call into a `try..catch` block.
+
+However, this doesn't help! This script actually leads to an uncaught error in console!
+
+Why? How to avoid it?
\ No newline at end of file
diff --git a/1-js/11-async/08-async-await/article.md b/1-js/11-async/08-async-await/article.md
index 4c50228666..aff13526be 100644
--- a/1-js/11-async/08-async-await/article.md
+++ b/1-js/11-async/08-async-await/article.md
@@ -1,10 +1,18 @@
# Async/await
+<<<<<<< HEAD
"async/await" と呼ばれる、より快適に promise を利用する特別な構文があります。驚くほど簡単に理解し、使用することができます。
## Async 関数
`async` キーワードから始めましょう。次のように関数の前に置くことができます:
+=======
+There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly easy to understand and use.
+
+## Async functions
+
+Let's start with the `async` keyword. It can be placed before a function, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
async function f() {
@@ -12,9 +20,15 @@ async function f() {
}
```
+<<<<<<< HEAD
関数の前の用語 "async" は1つの単純なことを意味します: 関数は常に promise を返します。コード中に `return <非 promise>` がある場合、JavaScript は自動的にその値を持つ 解決された promise にラップします。
例えば、上のコードは 結果 `1` を持つ解決された promise を返します。テストしてみましょう: t it:
+=======
+The word "async" before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
+
+For instance, this function returns a resolved promise with the result of `1`; let's test it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
@@ -24,7 +38,11 @@ async function f() {
f().then(alert); // 1
```
+<<<<<<< HEAD
...明示的に promise を返すこともでき、それは同じです:
+=======
+...We could explicitly return a promise, which would be the same:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
@@ -34,6 +52,7 @@ async function f() {
f().then(alert); // 1
```
+<<<<<<< HEAD
したがって、`async` は関数が promise を返すことを保証し、非promise をその中にラップします。シンプルですよね?しかし、それだけではありません。`async` 関数の中でのみ動作する別のキーワード `await` があります。これはとてもクールです。
## Await
@@ -48,6 +67,22 @@ let value = await promise;
キーワード `await` は promise が確定しその結果を返すまで、JavaScript を待機させます。 ult.
これは1秒で解決する promise の例です:
+=======
+So, `async` ensures that the function returns a promise, and wraps non-promises in it. Simple enough, right? But not only that. There's another keyword, `await`, that works only inside `async` functions, and it's pretty cool.
+
+## Await
+
+The syntax:
+
+```js
+// works only inside async functions
+let value = await promise;
+```
+
+The keyword `await` makes JavaScript wait until that promise settles and returns its result.
+
+Here's an example with a promise that resolves in 1 second:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
@@ -56,7 +91,11 @@ async function f() {
});
*!*
+<<<<<<< HEAD
let result = await promise; // promise が解決するまで待ちます (*)
+=======
+ let result = await promise; // wait until the promise resolves (*)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(result); // "done!"
@@ -65,6 +104,7 @@ async function f() {
f();
```
+<<<<<<< HEAD
関数の実行は行 `(*)` で "一時停止" し、promise が確定したときに再開し、`result` がその結果になります。 そのため、上のコードは1秒後に "done!" を表示します。
`await` は文字通り promise が確定するまで JavaScript を待ってから、その結果で続くことに注目しましょう。その間、エンジンは他のジョブ(他のスクリプトを実行し、イベントを処理するなど)を実行することができるため、CPUリソースを必要としません。
@@ -73,6 +113,16 @@ f();
````warn header="通常の関数で `await` を使うことはできません"
非async関数で `await` を使おうとした場合、構文エラーになります。:
+=======
+The function execution "pauses" at the line `(*)` and resumes when the promise settles, with `result` becoming its result. So the code above shows "done!" in one second.
+
+Let's emphasize: `await` literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn't cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc.
+
+It's just a more elegant syntax of getting the promise result than `promise.then`. And, it's easier to read and write.
+
+````warn header="Can't use `await` in regular functions"
+If we try to use `await` in a non-async function, there would be a syntax error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function f() {
@@ -83,6 +133,7 @@ function f() {
}
```
+<<<<<<< HEAD
関数の前に `async` を置き忘れた場合にこのエラーが発生します。先程言ったように、`await` は `async function` の中でのみ動作します。
````
@@ -90,10 +141,20 @@ function f() {
1. `.then` 呼び出しを `await` に置き換える必要があります。
2. また、機能させるために関数を `async` にする必要があります。
+=======
+We may get this error if we forget to put `async` before a function. As stated earlier, `await` only works inside an `async` function.
+````
+
+Let's take the `showAvatar()` example from the chapter and rewrite it using `async/await`:
+
+1. We'll need to replace `.then` calls with `await`.
+2. Also we should make the function `async` for them to work.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function showAvatar() {
+<<<<<<< HEAD
// JSON を読み込む
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
@@ -103,12 +164,27 @@ async function showAvatar() {
let githubUser = await githubResponse.json();
// アバターを表示する
+=======
+ // read our JSON
+ let response = await fetch('/article/promise-chaining/user.json');
+ let user = await response.json();
+
+ // read github user
+ let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
+ let githubUser = await githubResponse.json();
+
+ // show the avatar
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
+<<<<<<< HEAD
// 3秒待つ
+=======
+ // wait 3 seconds
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
@@ -119,6 +195,7 @@ async function showAvatar() {
showAvatar();
```
+<<<<<<< HEAD
非常にスッキリし、読みやすいですよね?前よりもはるかに良いです。
````smart header="`await` はトップレベルのコードでは動作しません"
@@ -128,15 +205,32 @@ showAvatar();
```js run module
// モジュールのトップレベルでコードが実行される想定です
+=======
+Pretty clean and easy to read, right? Much better than before.
+
+````smart header="Modern browsers allow top-level `await` in modules"
+In modern browsers, `await` on top level works just fine, when we're inside a module. We'll cover modules in article .
+
+For instance:
+
+```js run module
+// we assume this code runs at top level, inside a module
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
console.log(user);
```
+<<<<<<< HEAD
モジュール未使用、あるいは[古いブラウザ](https://caniuse.com/mdn-javascript_operators_await_top_level)でサポートが必要な場合、無名の async 関数でラップする方法があります。
次のようになります:
+=======
+If we're not using modules, or [older browsers](https://caniuse.com/mdn-javascript_operators_await_top_level) must be supported, there's a universal recipe: wrapping into an anonymous async function.
+
+Like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
(async () => {
@@ -148,10 +242,17 @@ console.log(user);
````
+<<<<<<< HEAD
````smart header="`await` は thenable を許容します"
`promise.then` のように、`await` は thenable オブジェクト(`then` メソッドを呼ぶことができるもの)を使うことができます。繰り返しになりますが、このアイデアは、サードパーティオブジェクトは promise ではなく、promise 互換である場合があるということです(`.then` をサポートしている場合、`await` で使えます)。
例えば、ここで `await` は `new Thenable(1)` を許容します:
+=======
+````smart header="`await` accepts \"thenables\""
+Like `promise.then`, `await` allows us to use thenable objects (those with a callable `then` method). The idea is that a third-party object may not be a promise, but promise-compatible: if it supports `.then`, that's enough to use it with `await`.
+
+Here's a demo `Thenable` class; the `await` below accepts its instances:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Thenable {
@@ -159,6 +260,7 @@ class Thenable {
this.num = num;
}
then(resolve, reject) {
+<<<<<<< HEAD
alert(resolve); // function() { native code }
// 1000ms 後に this.num*2 で解決する
setTimeout(() => resolve(this.num * 2), 1000); // (*)
@@ -167,6 +269,16 @@ class Thenable {
async function f() {
// 1秒待って、結果は 2 になる
+=======
+ alert(resolve);
+ // resolve with this.num*2 after 1000ms
+ setTimeout(() => resolve(this.num * 2), 1000); // (*)
+ }
+}
+
+async function f() {
+ // waits for 1 second, then result becomes 2
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let result = await new Thenable(1);
alert(result);
}
@@ -174,11 +286,19 @@ async function f() {
f();
```
+<<<<<<< HEAD
もし `await` が `.then` で非promise オブジェクトを得た場合、引数としてネイティブ関数 `resolve`, `reject` を提供しているメソッドを呼び出します。次に `await` はいずれかが呼ばれるまで待ち(上の例では、行 `(*)` です)、その結果で進みます。
````
````smart header="Async メソッド"
クラスメソッドもまた async になれます。ただ前に `async` を置くだけです。
+=======
+If `await` gets a non-promise object with `.then`, it calls that method providing the built-in functions `resolve` and `reject` as arguments (just as it does for a regular `Promise` executor). Then `await` waits until one of them is called (in the example above it happens in the line `(*)`) and then proceeds with the result.
+````
+
+````smart header="Async class methods"
+To declare an async class method, just prepend it with `async`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
class Waiter {
@@ -191,6 +311,7 @@ class Waiter {
new Waiter()
.wait()
+<<<<<<< HEAD
.then(alert); // 1
```
意味は同じです: 返却される値が promise であることを保証し、`await` を有効にします。
@@ -201,6 +322,18 @@ new Waiter()
もし promise が正常に解決すると、`await promise` は結果を返します。しかし拒否(reject) の場合はエラーをスローします。それはちょうどその行に `throw` 文があるように振る舞います。
このコードは:
+=======
+ .then(alert); // 1 (this is the same as (result => alert(result)))
+```
+The meaning is the same: it ensures that the returned value is a promise and enables `await`.
+
+````
+## Error handling
+
+If a promise resolves normally, then `await promise` returns the result. But in the case of a rejection, it throws the error, just as if there were a `throw` statement at that line.
+
+This code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
async function f() {
@@ -210,7 +343,11 @@ async function f() {
}
```
+<<<<<<< HEAD
...これと同じです:
+=======
+...is the same as this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
async function f() {
@@ -220,9 +357,15 @@ async function f() {
}
```
+<<<<<<< HEAD
実際には、promise を拒否するまでに時間がかかる場合があります。なので、`await` は待ち、その後エラーをスローします。
エラーは `try..catch` でキャッチすることができ、それは通常の `throw` と同じ方法です:
+=======
+In real situations, the promise may take some time before it rejects. In that case there will be a delay before `await` throws an error.
+
+We can catch that error using `try..catch`, the same way as a regular `throw`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
@@ -239,7 +382,11 @@ async function f() {
f();
```
+<<<<<<< HEAD
エラーの場合、コントロールは `catch` ブロックにジャンプします。複数行をラップすることも可能です:
+=======
+In the case of an error, the control jumps to the `catch` block. We can also wrap multiple lines:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
@@ -248,7 +395,11 @@ async function f() {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
+<<<<<<< HEAD
// fetch と response.json 両方のエラーをキャッチ
+=======
+ // catches errors both in fetch and response.json
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(err);
}
}
@@ -256,19 +407,28 @@ async function f() {
f();
```
+<<<<<<< HEAD
もし `try..catch` がない場合、async 関数 `f()` の呼び出しによって生成された promise は拒否されます。それを処理にするには `.catch` を追加します。:
+=======
+If we don't have `try..catch`, then the promise generated by the call of the async function `f()` becomes rejected. We can append `.catch` to handle it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
async function f() {
let response = await fetch('http://no-such-url');
}
+<<<<<<< HEAD
// f() は拒否された promise になる
+=======
+// f() becomes a rejected promise
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
f().catch(alert); // TypeError: failed to fetch // (*)
*/!*
```
+<<<<<<< HEAD
そこに `.catch` を追加し忘れると、未処理の promise エラーを得ます(それはコンソールで見えます)。チャプター で説明した通り、グローバルイベントハンドラを使用することでこのようなエラーをキャッチすることができます。
@@ -283,6 +443,22 @@ f().catch(alert); // TypeError: failed to fetch // (*)
```js
// 結果の配列をまつ
+=======
+If we forget to add `.catch` there, then we get an unhandled promise error (viewable in the console). We can catch such errors using a global `unhandledrejection` event handler as described in the chapter .
+
+
+```smart header="`async/await` and `promise.then/catch`"
+When we use `async/await`, we rarely need `.then`, because `await` handles the waiting for us. And we can use a regular `try..catch` instead of `.catch`. That's usually (but not always) more convenient.
+
+But at the top level of the code, when we're outside any `async` function, we're syntactically unable to use `await`, so it's a normal practice to add `.then/catch` to handle the final result or falling-through error, like in the line `(*)` of the example above.
+```
+
+````smart header="`async/await` works well with `Promise.all`"
+When we need to wait for multiple promises, we can wrap them in `Promise.all` and then `await`:
+
+```js
+// wait for the array of results
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
let results = await Promise.all([
fetch(url1),
fetch(url2),
@@ -290,6 +466,7 @@ let results = await Promise.all([
]);
```
+<<<<<<< HEAD
エラーが発生した場合、それは通常通り伝搬します: 失敗した promise から `Promise.all` に伝播し、呼び出しのまわりで `try..catch` を使ってキャッチができる例外になります。
````
@@ -309,3 +486,24 @@ promise の前の `await` キーワードは、 promise が確定するまで Ja
共に、読み書きするのが簡単な非同期コードを書くことができる素晴らしいフレームワークを提供します。
`async/await` と一緒に `promise.then/catch` を書く必要はほとんどありませんが、時には(例えば最も外側のスコープで)これらのメソッドを使わなければならないことがあるので、これらが promise に基づいていることを忘れてはいけません。 また、`Promise.all` は同時に多くのタスクを待つ良い方法です。
+=======
+In the case of an error, it propagates as usual, from the failed promise to `Promise.all`, and then becomes an exception that we can catch using `try..catch` around the call.
+
+````
+
+## Summary
+
+The `async` keyword before a function has two effects:
+
+1. Makes it always return a promise.
+2. Allows `await` to be used in it.
+
+The `await` keyword before a promise makes JavaScript wait until that promise settles, and then:
+
+1. If it's an error, an exception is generated — same as if `throw error` were called at that very place.
+2. Otherwise, it returns the result.
+
+Together they provide a great framework to write asynchronous code that is easy to both read and write.
+
+With `async/await` we rarely need to write `promise.then/catch`, but we still shouldn't forget that they are based on promises, because sometimes (e.g. in the outermost scope) we have to use these methods. Also `Promise.all` is nice when we are waiting for many tasks simultaneously.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/11-async/index.md b/1-js/11-async/index.md
index a626cee4f0..0fd95aff10 100644
--- a/1-js/11-async/index.md
+++ b/1-js/11-async/index.md
@@ -1,2 +1,6 @@
+<<<<<<< HEAD
# Promise, async/await
+=======
+# Promises, async/await
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/solution.md b/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/solution.md
index 0497128889..36dc19f166 100644
--- a/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/solution.md
+++ b/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/solution.md
@@ -3,7 +3,11 @@ function* pseudoRandom(seed) {
let value = seed;
while(true) {
+<<<<<<< HEAD
value = value * 16807 % 2147483647
+=======
+ value = value * 16807 % 2147483647;
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
yield value;
}
@@ -16,7 +20,11 @@ alert(generator.next().value); // 282475249
alert(generator.next().value); // 1622650073
```
+<<<<<<< HEAD
注意してください。次のように通常の関数でも同じことができます:
+=======
+Please note, the same can be done with a regular function, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function pseudoRandom(seed) {
@@ -35,4 +43,8 @@ alert(generator()); // 282475249
alert(generator()); // 1622650073
```
+<<<<<<< HEAD
これは、このコンテキストでは問題ありません。しかし、どこかで役立つかのしれない `for..of` を使ったイテレートや、ジェネレータの合成を使うことはできなくなります。
+=======
+That also works. But then we lose ability to iterate with `for..of` and to use generator composition, that may be useful elsewhere.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/task.md b/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/task.md
index 17d390a2f6..b883b65dea 100644
--- a/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/task.md
+++ b/1-js/12-generators-iterators/1-generators/01-pseudo-random-generator/task.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# 疑似乱数ジェネレータ
ランダムデータが必要となる多くの場面があります。
@@ -10,11 +11,25 @@ JavaScript では `Math.random()` を使うことができます。しかし、
そのために、"シード疑似乱数ジェネレータ" と呼ばれるものが使われます。それらは最初の値である "シード(種)" を取り、以降公式を使って次の値を生成します。同じシードは同じ一覧の数列を生成するので、フロー全体を簡単に再現することができます。繰り返すのに覚えておく必要があるのはシードだけです。
これは、このような公式の例で、幾分か一様に分布した値を生成します。:
+=======
+# Pseudo-random generator
+
+There are many areas where we need random data.
+
+One of them is testing. We may need random data: text, numbers, etc. to test things out well.
+
+In JavaScript, we could use `Math.random()`. But if something goes wrong, we'd like to be able to repeat the test, using exactly the same data.
+
+For that, so called "seeded pseudo-random generators" are used. They take a "seed", the first value, and then generate the next ones using a formula so that the same seed yields the same sequence, and hence the whole flow is easily reproducible. We only need to remember the seed to repeat it.
+
+An example of such formula, that generates somewhat uniformly distributed values:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
next = previous * 16807 % 2147483647
```
+<<<<<<< HEAD
シードに `1` を使うと、値は次のようになります:
1. `16807`
2. `282475249`
@@ -24,6 +39,17 @@ next = previous * 16807 % 2147483647
このタスクは、`seed` を取り、この式でジェネレータを生成するジェネレータ関数 `pseudoRandom(seed)` を作成することです。
使用例:
+=======
+If we use `1` as the seed, the values will be:
+1. `16807`
+2. `282475249`
+3. `1622650073`
+4. ...and so on...
+
+The task is to create a generator function `pseudoRandom(seed)` that takes `seed` and creates the generator with this formula.
+
+Usage example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let generator = pseudoRandom(1);
diff --git a/1-js/12-generators-iterators/1-generators/article.md b/1-js/12-generators-iterators/1-generators/article.md
index b1907aa307..7a72db8d30 100644
--- a/1-js/12-generators-iterators/1-generators/article.md
+++ b/1-js/12-generators-iterators/1-generators/article.md
@@ -1,3 +1,4 @@
+<<<<<<< HEAD
# ジェネレータ
@@ -10,6 +11,19 @@
ジェネレータを作成するには、特別な構文構造: `function*`、いわゆる "ジェネレータ関数" を使用する必要があります。
このようになります:
+=======
+# Generators
+
+Regular functions return only one, single value (or nothing).
+
+Generators can return ("yield") multiple values, one after another, on-demand. They work great with [iterables](info:iterable), allowing to create data streams with ease.
+
+## Generator functions
+
+To create a generator, we need a special syntax construct: `function*`, so-called "generator function".
+
+It looks like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
function* generateSequence() {
@@ -19,6 +33,7 @@ function* generateSequence() {
}
```
+<<<<<<< HEAD
`generateSequence()` が呼ばれたとき、コードは実行されません。代わりに、"ジェネレータ" と呼ばれる特別なオブジェクトを返します。
```js
@@ -35,6 +50,37 @@ let generator = generateSequence();
ジェネレータのメインのメソッドは `next()` です。呼ばれると、最も近い `yield ` 文まで実行を再開します。その後、実行は一時停止し、値は外部のコードに返却されます。
例えば、ここではジェネレータを作成し、最初に戻される値を取得しています:
+=======
+Generator functions behave differently from regular ones. When such function is called, it doesn't run its code. Instead it returns a special object, called "generator object", to manage the execution.
+
+Here, take a look:
+
+```js run
+function* generateSequence() {
+ yield 1;
+ yield 2;
+ return 3;
+}
+
+// "generator function" creates "generator object"
+let generator = generateSequence();
+*!*
+alert(generator); // [object Generator]
+*/!*
+```
+
+The function code execution hasn't started yet:
+
+
+
+The main method of a generator is `next()`. When called, it runs the execution until the nearest `yield ` statement (`value` can be omitted, then it's `undefined`). Then the function execution pauses, and the yielded `value` is returned to the outer code.
+
+The result of `next()` is always an object with two properties:
+- `value`: the yielded value.
+- `done`: `true` if the function code has finished, otherwise `false`.
+
+For instance, here we create the generator and get its first yielded value:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence() {
@@ -52,6 +98,7 @@ let one = generator.next();
alert(JSON.stringify(one)); // {value: 1, done: false}
```
+<<<<<<< HEAD
`next()` の結果は常にオブジェクトです:
- `value`: 戻された値
- `done`: コードがまだ終わっていない場合は `false`, そうでなければ `true`.
@@ -61,6 +108,13 @@ alert(JSON.stringify(one)); // {value: 1, done: false}

再び `generator.next()` を呼びましょう。実行が再開し、次の `yield` を貸します。:
+=======
+As of now, we got the first value only, and the function execution is on the second line:
+
+
+
+Let's call `generator.next()` again. It resumes the code execution and returns the next `yield`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let two = generator.next();
@@ -70,7 +124,11 @@ alert(JSON.stringify(two)); // {value: 2, done: false}

+<<<<<<< HEAD
そして、3回目を呼び出すと、実行は関数を終了する `return` 文に到達します。
+=======
+And, if we call it a third time, the execution reaches the `return` statement that finishes the function:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let three = generator.next();
@@ -80,6 +138,7 @@ alert(JSON.stringify(three)); // {value: 3, *!*done: true*/!*}

+<<<<<<< HEAD
これでジェネレータが済みました。`done:true` でそれが判断でき、`value:3` を最終結果として処理します。
新たな `generator.next()` 呼び出しはこれ以上意味をなしません。それを行っても、同じオブジェクト `{done: true}` が返却されます。
@@ -99,6 +158,23 @@ alert(JSON.stringify(three)); // {value: 3, *!*done: true*/!*}
おそらく `next()` メソッドを見て既に推測していると思いますが、ジェネレータは [反復可能(iterable)](info:iterable)です。
`for..of` によって、値をループすることができます:
+=======
+Now the generator is done. We should see it from `done:true` and process `value:3` as the final result.
+
+New calls to `generator.next()` don't make sense any more. If we do them, they return the same object: `{done: true}`.
+
+```smart header="`function* f(…)` or `function *f(…)`?"
+Both syntaxes are correct.
+
+But usually the first syntax is preferred, as the star `*` denotes that it's a generator function, it describes the kind, not the name, so it should stick with the `function` keyword.
+```
+
+## Generators are iterable
+
+As you probably already guessed looking at the `next()` method, generators are [iterable](info:iterable).
+
+We can loop over their values using `for..of`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence() {
@@ -110,6 +186,7 @@ function* generateSequence() {
let generator = generateSequence();
for(let value of generator) {
+<<<<<<< HEAD
alert(value); // 1, 次に 2
}
```
@@ -119,6 +196,17 @@ for(let value of generator) {
...しかし、注意してください: 上の例では `1` が表示された後 `2` が表示され、それですべてです。`3` は表示されません!
これは、`done: true` のとき、for-of イテレーションは最後の `value` を無視するからです。なので、すべての結果を `for..of` で表示したい場合は、それらを `yield` で返さなければなりません:
+=======
+ alert(value); // 1, then 2
+}
+```
+
+Looks a lot nicer than calling `.next().value`, right?
+
+...But please note: the example above shows `1`, then `2`, and that's all. It doesn't show `3`!
+
+It's because `for..of` iteration ignores the last `value`, when `done: true`. So, if we want all results to be shown by `for..of`, we must return them with `yield`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence() {
@@ -132,11 +220,19 @@ function* generateSequence() {
let generator = generateSequence();
for(let value of generator) {
+<<<<<<< HEAD
alert(value); // 1, 次に 2, 次に 3
}
```
当然、ジェネレータは反復可能なので、スプレッド演算子`...` のような、関連するすべての機能を呼び出すことができます。:
+=======
+ alert(value); // 1, then 2, then 3
+}
+```
+
+As generators are iterable, we can call all related functionality, e.g. the spread syntax `...`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence() {
@@ -150,6 +246,7 @@ let sequence = [0, ...generateSequence()];
alert(sequence); // 0, 1, 2, 3
```
+<<<<<<< HEAD
上のコードでは、`...generateSequence()` は iterable をアイテムの配列に変換します(スプレッド演算子についてはチャプター [](info:rest-parameters-spread-operator#spread-operator)) を読んでください)。
## 反復可能(iterable)の代わりにジェネレータを使用する
@@ -157,23 +254,45 @@ alert(sequence); // 0, 1, 2, 3
少し前、チャプター [](info:iterable) で、値 `from..to` を返す反復可能な `range` オブジェクトを作りました。
ここで、そのコードを思い出しましょう。:
+=======
+In the code above, `...generateSequence()` turns the iterable generator object into an array of items (read more about the spread syntax in the chapter [](info:rest-parameters-spread#spread-syntax))
+
+## Using generators for iterables
+
+Some time ago, in the chapter [](info:iterable) we created an iterable `range` object that returns values `from..to`.
+
+Here, let's remember the code:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
from: 1,
to: 5,
+<<<<<<< HEAD
// for..of は最初にこのメソッドを一度呼び出します
[Symbol.iterator]() {
// ...これは iterator オブジェクトを返します:
// 以降, for..of はそのオブジェクトでのみ機能し、次の値を要求します。
+=======
+ // for..of range calls this method once in the very beginning
+ [Symbol.iterator]() {
+ // ...it returns the iterator object:
+ // onward, for..of works only with that object, asking it for next values
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
return {
current: this.from,
last: this.to,
+<<<<<<< HEAD
// next() は for..of ループの各イテレーションで呼ばれます
next() {
// 値をオブジェクトとして返す必要があります {done:.., value :...}
+=======
+ // next() is called on each iteration by the for..of loop
+ next() {
+ // it should return the value as an object {done:.., value :...}
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
@@ -184,6 +303,7 @@ let range = {
}
};
+<<<<<<< HEAD
alert([...range]); // 1,2,3,4,5
```
@@ -206,13 +326,26 @@ alert(sequence); // 1, 2, 3, 4, 5
## Symbol.iterator からジェネレータへの変換
ジェネレータを `Symbol.iterator` として提供することで、両方の世界からベストを得ることができます:
+=======
+// iteration over range returns numbers from range.from to range.to
+alert([...range]); // 1,2,3,4,5
+```
+
+We can use a generator function for iteration by providing it as `Symbol.iterator`.
+
+Here's the same `range`, but much more compact:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
from: 1,
to: 5,
+<<<<<<< HEAD
*[Symbol.iterator]() { // [Symbol.iterator]: function*() の短縮記法
+=======
+ *[Symbol.iterator]() { // a shorthand for [Symbol.iterator]: function*()
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for(let value = this.from; value <= this.to; value++) {
yield value;
}
@@ -222,6 +355,7 @@ let range = {
alert( [...range] ); // 1,2,3,4,5
```
+<<<<<<< HEAD
`range` オブジェクトはいま反復可能です。
これは非常に上手く機能します。なぜなら、`range[Symbol.iterator]` が呼ばれたとき、:
@@ -255,6 +389,46 @@ alert( [...range] ); // 1,2,3,4,5
通常の関数では、複数の別々の関数からの結果をまとめるためには、それらを呼び出し、結果を格納し、最後に結合します。
ジェネレータの場合は、次のようによりスマートに行うことができます:
+=======
+That works, because `range[Symbol.iterator]()` now returns a generator, and generator methods are exactly what `for..of` expects:
+- it has a `.next()` method
+- that returns values in the form `{value: ..., done: true/false}`
+
+That's not a coincidence, of course. Generators were added to JavaScript language with iterators in mind, to implement them easily.
+
+The variant with a generator is much more concise than the original iterable code of `range`, and keeps the same functionality.
+
+```smart header="Generators may generate values forever"
+In the examples above we generated finite sequences, but we can also make a generator that yields values forever. For instance, an unending sequence of pseudo-random numbers.
+
+That surely would require a `break` (or `return`) in `for..of` over such generator. Otherwise, the loop would repeat forever and hang.
+```
+
+## Generator composition
+
+Generator composition is a special feature of generators that allows to transparently "embed" generators in each other.
+
+For instance, we have a function that generates a sequence of numbers:
+
+```js
+function* generateSequence(start, end) {
+ for (let i = start; i <= end; i++) yield i;
+}
+```
+
+Now we'd like to reuse it to generate a more complex sequence:
+- first, digits `0..9` (with character codes 48..57),
+- followed by uppercase alphabet letters `A..Z` (character codes 65..90)
+- followed by lowercase alphabet letters `a..z` (character codes 97..122)
+
+We can use this sequence e.g. to create passwords by selecting characters from it (could add syntax characters as well), but let's generate it first.
+
+In a regular function, to combine results from multiple other functions, we call them, store the results, and then join at the end.
+
+For generators, there's a special `yield*` syntax to "embed" (compose) one generator into another.
+
+The composed generator:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence(start, end) {
@@ -285,9 +459,15 @@ for(let code of generatePasswordCodes()) {
alert(str); // 0..9A..Za..z
```
+<<<<<<< HEAD
この例にある特別な `yield*` ディレクティブは合成を担当します。これは、別のジェネレータに実行を *委譲(デリゲート)* します。あるいは、単純に言うと、ジェネレータを実行し、あたかもそれらが呼び出し元のジェネレータ自体によって行われたかのように、それらの yield を外部に透過的に転送します。
結果は、入れ子のジェネレータのコードがインライン展開された場合と同じです。:
+=======
+The `yield*` directive *delegates* the execution to another generator. This term means that `yield* gen` iterates over the generator `gen` and transparently forwards its yields outside. As if the values were yielded by the outer generator.
+
+The result is the same as if we inlined the code from nested generators:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence(start, end) {
@@ -318,6 +498,7 @@ for(let code of generateAlphaNum()) {
alert(str); // 0..9A..Za..z
```
+<<<<<<< HEAD
ジェネレータの合成は、あるジェネレータのフローを別のジェネレータに挿入するための、自然な方法です。
入れ子のジェネレータからの値のフローが無限の場合でも動作します。それはシンプルで中間結果を格納するための余分なメモリを必要としません。
@@ -333,12 +514,30 @@ alert(str); // 0..9A..Za..z
そうするためには、引数を持つ `generator.next(arg)` を呼び出す必要があります。この引数は `yield` の結果になります。
例を見てみましょう:
+=======
+A generator composition is a natural way to insert a flow of one generator into another. It doesn't use extra memory to store intermediate results.
+
+## "yield" is a two-way street
+
+Until this moment, generators were similar to iterable objects, with a special syntax to generate values. But in fact they are much more powerful and flexible.
+
+That's because `yield` is a two-way street: it not only returns the result to the outside, but also can pass the value inside the generator.
+
+To do so, we should call `generator.next(arg)`, with an argument. That argument becomes the result of `yield`.
+
+Let's see an example:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* gen() {
*!*
+<<<<<<< HEAD
// 質問を外側のコードに渡して答えを待ちます
let result = yield "2 + 2?"; // (*)
+=======
+ // Pass a question to the outer code and wait for an answer
+ let result = yield "2 + 2 = ?"; // (*)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
alert(result);
@@ -346,13 +545,20 @@ function* gen() {
let generator = gen();
+<<<<<<< HEAD
let question = generator.next().value; // <-- yield は値を返します
generator.next(4); // --> 結果をジェネレータに渡します
+=======
+let question = generator.next().value; // <-- yield returns the value
+
+generator.next(4); // --> pass the result into the generator
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```

+<<<<<<< HEAD
1. 最初の呼び出し `generator.next()` は常に引数なしです。実行を開始し、最初の `yield` ("2+2?") の結果を返します。この時点で、ジェネレータは実行を一時停止します(依然としてその行にいます)。
2. 次に、上の図にあるように、`yield` の結果は呼び出しコードの `question` 変数に入ります。
3. `generator.next(4)` でジェネレータが再開し、結果として `4` が入ります: `let result = 4`
@@ -375,19 +581,52 @@ function* gen() {
alert(ask1); // 4
let ask2 = yield "3 * 3?"
+=======
+1. The first call `generator.next()` should be always made without an argument (the argument is ignored if passed). It starts the execution and returns the result of the first `yield "2+2=?"`. At this point the generator pauses the execution, while staying on the line `(*)`.
+2. Then, as shown at the picture above, the result of `yield` gets into the `question` variable in the calling code.
+3. On `generator.next(4)`, the generator resumes, and `4` gets in as the result: `let result = 4`.
+
+Please note, the outer code does not have to immediately call `next(4)`. It may take time. That's not a problem: the generator will wait.
+
+For instance:
+
+```js
+// resume the generator after some time
+setTimeout(() => generator.next(4), 1000);
+```
+
+As we can see, unlike regular functions, a generator and the calling code can exchange results by passing values in `next/yield`.
+
+To make things more obvious, here's another example, with more calls:
+
+```js run
+function* gen() {
+ let ask1 = yield "2 + 2 = ?";
+
+ alert(ask1); // 4
+
+ let ask2 = yield "3 * 3 = ?"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert(ask2); // 9
}
let generator = gen();
+<<<<<<< HEAD
alert( generator.next().value ); // "2 + 2?"
alert( generator.next(4).value ); // "3 * 3?"
+=======
+alert( generator.next().value ); // "2 + 2 = ?"
+
+alert( generator.next(4).value ); // "3 * 3 = ?"
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
alert( generator.next(9).done ); // true
```
+<<<<<<< HEAD
実行の図です:

@@ -409,15 +648,46 @@ alert( generator.next(9).done ); // true
エラーを `yield` に渡すには、`generator.throw(err)` を呼び出す必要があります。この場合、`err` は `yield` のある行に投げられます。
例えば、ここで `"2 + 2?"` の yield はエラーになります:
+=======
+The execution picture:
+
+
+
+1. The first `.next()` starts the execution... It reaches the first `yield`.
+2. The result is returned to the outer code.
+3. The second `.next(4)` passes `4` back to the generator as the result of the first `yield`, and resumes the execution.
+4. ...It reaches the second `yield`, that becomes the result of the generator call.
+5. The third `next(9)` passes `9` into the generator as the result of the second `yield` and resumes the execution that reaches the end of the function, so `done: true`.
+
+It's like a "ping-pong" game. Each `next(value)` (excluding the first one) passes a value into the generator, that becomes the result of the current `yield`, and then gets back the result of the next `yield`.
+
+## generator.throw
+
+As we observed in the examples above, the outer code may pass a value into the generator, as the result of `yield`.
+
+...But it can also initiate (throw) an error there. That's natural, as an error is a kind of result.
+
+To pass an error into a `yield`, we should call `generator.throw(err)`. In that case, the `err` is thrown in the line with that `yield`.
+
+For instance, here the yield of `"2 + 2 = ?"` leads to an error:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* gen() {
try {
+<<<<<<< HEAD
let result = yield "2 + 2?"; // (1)
alert("The execution does not reach here, because the exception is thrown above");
} catch(e) {
alert(e); // エラーを表示します
+=======
+ let result = yield "2 + 2 = ?"; // (1)
+
+ alert("The execution does not reach here, because the exception is thrown above");
+ } catch(e) {
+ alert(e); // shows the error
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
}
@@ -430,6 +700,7 @@ generator.throw(new Error("The answer is not found in my database")); // (2)
*/!*
```
+<<<<<<< HEAD
エラーは、行 `(2)` でジェネレータにスローされ、`yield` のある行 `(1)` で例外となります。上の例では、`try..catch` がそれをキャッチし表示しています。
キャッチしない場合、他の例外のように、ジェネレータは呼び出しコードで "落ちます"。
@@ -439,6 +710,17 @@ generator.throw(new Error("The answer is not found in my database")); // (2)
```js run
function* generate() {
let result = yield "2 + 2?"; // この行でエラー
+=======
+The error, thrown into the generator at line `(2)` leads to an exception in line `(1)` with `yield`. In the example above, `try..catch` catches it and shows it.
+
+If we don't catch it, then just like any exception, it "falls out" the generator into the calling code.
+
+The current line of the calling code is the line with `generator.throw`, labelled as `(2)`. So we can catch it here, like this:
+
+```js run
+function* generate() {
+ let result = yield "2 + 2 = ?"; // Error in this line
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
let generator = generate();
@@ -449,11 +731,16 @@ let question = generator.next().value;
try {
generator.throw(new Error("The answer is not found in my database"));
} catch(e) {
+<<<<<<< HEAD
alert(e); // エラーを表示します
+=======
+ alert(e); // shows the error
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
*/!*
```
+<<<<<<< HEAD
ここでエラーをキャッチしなければ、通常どおり、外部の呼び出しコード(あれば)へ渡され、キャッチされなければスクリプトが強制終了します。
## サマリ
@@ -467,3 +754,40 @@ try {
また、次のチャプターでは、非同期のジェネレータについて学びます。それは `for` ループで非同期的に生成されたデータをのストリームを読むのに使われます。
web プログラミングでは、しばしばストリーミングデータを扱います。e.g. ページングされた結果を取得する必要があるため、これはとても重要なユースケースです。
+=======
+If we don't catch the error there, then, as usual, it falls through to the outer calling code (if any) and, if uncaught, kills the script.
+
+## generator.return
+
+`generator.return(value)` finishes the generator execution and return the given `value`.
+
+```js
+function* gen() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+const g = gen();
+
+g.next(); // { value: 1, done: false }
+g.return('foo'); // { value: "foo", done: true }
+g.next(); // { value: undefined, done: true }
+```
+
+If we again use `generator.return()` in a completed generator, it will return that value again ([MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return)).
+
+Often we don't use it, as most of time we want to get all returning values, but it can be useful when we want to stop generator in a specific condition.
+
+## Summary
+
+- Generators are created by generator functions `function* f(…) {…}`.
+- Inside generators (only) there exists a `yield` operator.
+- The outer code and the generator may exchange results via `next/yield` calls.
+
+In modern JavaScript, generators are rarely used. But sometimes they come in handy, because the ability of a function to exchange data with the calling code during the execution is quite unique. And, surely, they are great for making iterable objects.
+
+Also, in the next chapter we'll learn async generators, which are used to read streams of asynchronously generated data (e.g paginated fetches over a network) in `for await ... of` loops.
+
+In web-programming we often work with streamed data, so that's another very important use case.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/1-generators/generateSequence-2.svg b/1-js/12-generators-iterators/1-generators/generateSequence-2.svg
index 4c64e983e1..b598c6d30e 100644
--- a/1-js/12-generators-iterators/1-generators/generateSequence-2.svg
+++ b/1-js/12-generators-iterators/1-generators/generateSequence-2.svg
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/1-generators/generateSequence-3.svg b/1-js/12-generators-iterators/1-generators/generateSequence-3.svg
index 0af8e9efdc..720c88d523 100644
--- a/1-js/12-generators-iterators/1-generators/generateSequence-3.svg
+++ b/1-js/12-generators-iterators/1-generators/generateSequence-3.svg
@@ -1 +1,5 @@
-
\ No newline at end of file
+<<<<<<< HEAD
+
+=======
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/2-async-iterators-generators/article.md b/1-js/12-generators-iterators/2-async-iterators-generators/article.md
index 404f0803d2..9a163d2797 100644
--- a/1-js/12-generators-iterators/2-async-iterators-generators/article.md
+++ b/1-js/12-generators-iterators/2-async-iterators-generators/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# 非同期イテレーションとジェネレータ
非同期イテレーションを使用すると、要求に応じて非同期に来るデータに対して反復処理することができます。例えば、ネットワーク経由でチャンクごとに何かをダウンロードする場合です。そして、非同期ジェネレータはそれをさらに便利にします。
@@ -10,6 +11,19 @@
反復可能(iterable)についてのトピックを思い出しましょう。
ここでは `range` のようなオブジェクトがあると考えます:
+=======
+# Async iteration and generators
+
+Asynchronous iteration allow us to iterate over data that comes asynchronously, on-demand. Like, for instance, when we download something chunk-by-chunk over a network. And asynchronous generators make it even more convenient.
+
+Let's see a simple example first, to grasp the syntax, and then review a real-life use case.
+
+## Recall iterables
+
+Let's recall the topic about iterables.
+
+The idea is that we have an object, such as `range` here:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let range = {
from: 1,
@@ -17,6 +31,7 @@ let range = {
};
```
+<<<<<<< HEAD
そして、これに対して `for(value of range)` のように `for..of` を使用して、`1` から `5` までの値を取得したいとします。
つまり、オブジェクトに *反復する機能* を追加したい、です。
@@ -28,6 +43,19 @@ let range = {
- `next()` は `{done: true/false, value:}` の形式の値の返却が必要で、`done:true` はループが終わりであることを意味します。
以下は、反復可能な `range` の実装です:
+=======
+...And we'd like to use `for..of` loop on it, such as `for(value of range)`, to get values from `1` to `5`.
+
+In other words, we want to add an *iteration ability* to the object.
+
+That can be implemented using a special method with the name `Symbol.iterator`:
+
+- This method is called in by the `for..of` construct when the loop is started, and it should return an object with the `next` method.
+- For each iteration, the `next()` method is invoked for the next value.
+- The `next()` should return a value in the form `{done: true/false, value:}`, where `done:true` means the end of the loop.
+
+Here's an implementation for the iterable `range`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
@@ -35,14 +63,22 @@ let range = {
to: 5,
*!*
+<<<<<<< HEAD
[Symbol.iterator]() { // for..of の最初に一度呼ばれます
+=======
+ [Symbol.iterator]() { // called once, in the beginning of for..of
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
return {
current: this.from,
last: this.to,
*!*
+<<<<<<< HEAD
next() { // 各イテレーションで呼ばれ、次の値を取得します
+=======
+ next() { // called every iteration, to get the next value
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*/!*
if (this.current <= this.last) {
return { done: false, value: this.current++ };
@@ -59,6 +95,7 @@ for(let value of range) {
}
```
+<<<<<<< HEAD
不明点があれば、通常のイテレータの詳細について [](info:iterable) を参照してください。
## 非同期の反復可能
@@ -78,6 +115,27 @@ for(let value of range) {
最初の例として、先程と同様、反復可能な `range` オブジェクトを作成しましょう。ですが、今度は1秒毎に値を非同期的に返します。:
やるべきことは、上のコードに対し少し置き換えるだけです:
+=======
+If anything is unclear, please visit the chapter [](info:iterable), it gives all the details about regular iterables.
+
+## Async iterables
+
+Asynchronous iteration is needed when values come asynchronously: after `setTimeout` or another kind of delay.
+
+The most common case is that the object needs to make a network request to deliver the next value, we'll see a real-life example of it a bit later.
+
+To make an object iterable asynchronously:
+
+1. Use `Symbol.asyncIterator` instead of `Symbol.iterator`.
+2. The `next()` method should return a promise (to be fulfilled with the next value).
+ - The `async` keyword handles it, we can simply make `async next()`.
+3. To iterate over such an object, we should use a `for await (let item of iterable)` loop.
+ - Note the `await` word.
+
+As a starting example, let's make an iterable `range` object, similar like the one before, but now it will return values asynchronously, one per second.
+
+All we need to do is to perform a few replacements in the code above:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
@@ -96,7 +154,11 @@ let range = {
*/!*
*!*
+<<<<<<< HEAD
// async next の中で、 "await" が使えます
+=======
+ // note: we can use "await" inside the async next:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
await new Promise(resolve => setTimeout(resolve, 1000)); // (3)
*/!*
@@ -121,6 +183,7 @@ let range = {
})()
```
+<<<<<<< HEAD
ご覧の通り、構成は通常のイテレータと同様です:
1. オブジェクトを非同期的に反復可能にするために、`Symbol.asyncIterator` メソッドが必要です。 `(1)`
@@ -140,17 +203,45 @@ let range = {
通常の、同期的なイテレータを要する機能は、非同期イテレータでは動作しません。
例えば、スプレッド演算子は動作しません:
+=======
+As we can see, the structure is similar to regular iterators:
+
+1. To make an object asynchronously iterable, it must have a method `Symbol.asyncIterator` `(1)`.
+2. This method must return the object with `next()` method returning a promise `(2)`.
+3. The `next()` method doesn't have to be `async`, it may be a regular method returning a promise, but `async` allows us to use `await`, so that's convenient. Here we just delay for a second `(3)`.
+4. To iterate, we use `for await(let value of range)` `(4)`, namely add "await" after "for". It calls `range[Symbol.asyncIterator]()` once, and then its `next()` for values.
+
+Here's a small table with the differences:
+
+| | Iterators | Async iterators |
+|-------|-----------|-----------------|
+| Object method to provide iterator | `Symbol.iterator` | `Symbol.asyncIterator` |
+| `next()` return value is | any value | `Promise` |
+| to loop, use | `for..of` | `for await..of` |
+
+````warn header="The spread syntax `...` doesn't work asynchronously"
+Features that require regular, synchronous iterators, don't work with asynchronous ones.
+
+For instance, a spread syntax won't work:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
alert( [...range] ); // Error, no Symbol.iterator
```
+<<<<<<< HEAD
`Symbol.asyncIterator` ではなく、`Symbol.iterator` があることを期待しているので、これは当然の結果です。
また、`for..of` のケースに対しても同様です: `await` なしの構文は `Symbol.iterator` を必要とします。
+=======
+That's natural, as it expects to find `Symbol.iterator`, not `Symbol.asyncIterator`.
+
+It's also the case for `for..of`: the syntax without `await` needs `Symbol.iterator`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
````
## Recall generators
+<<<<<<< HEAD
ここでジェネレータを思い出しましょう。ジェネレータを使用すると、イテレーションのコードをはるかに短くすることができます。ほとんどの場合、反復可能にしたい場合、ジェネレータを使用します。
単純にするために、いくつかの重要な点を省略すると、ジェネレータは "値を生成(yield)する関数" です。この詳細は [](info:generators) で説明しています。
@@ -158,6 +249,15 @@ alert( [...range] ); // Error, no Symbol.iterator
ジェネレータは `function*` ( * に注目)でラベル付けされたもので、値を生成すのに `yield` を使用します。ジェネレータをループするのに `for..of` が利用できます。
この例は `start` から end` までの一連の値を生成します:
+=======
+Now let's recall generators, as they allow to make iteration code much shorter. Most of the time, when we'd like to make an iterable, we'll use generators.
+
+For sheer simplicity, omitting some important stuff, they are "functions that generate (yield) values". They are explained in detail in the chapter [](info:generators).
+
+Generators are labelled with `function*` (note the star) and use `yield` to generate a value, then we can use `for..of` to loop over them.
+
+This example generates a sequence of values from `start` to `end`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
function* generateSequence(start, end) {
@@ -171,7 +271,11 @@ for(let value of generateSequence(1, 5)) {
}
```
+<<<<<<< HEAD
すでにご存知の通り、オブジェクトを反復可能にするには `Symbol.iterator` の追加が必要です。
+=======
+As we already know, to make an object iterable, we should add `Symbol.iterator` to it.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
let range = {
@@ -185,14 +289,22 @@ let range = {
}
```
+<<<<<<< HEAD
`Symbol.iterator` の一般的なプラクティスはジェネレータを返すことで、以下のようにコードをより短くできます:
+=======
+A common practice for `Symbol.iterator` is to return a generator, it makes the code shorter, as you can see:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
from: 1,
to: 5,
+<<<<<<< HEAD
*[Symbol.iterator]() { // [Symbol.iterator]: function*() の短縮形
+=======
+ *[Symbol.iterator]() { // a shorthand for [Symbol.iterator]: function*()
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
for(let value = this.from; value <= this.to; value++) {
yield value;
}
@@ -204,6 +316,7 @@ for(let value of range) {
}
```
+<<<<<<< HEAD
より詳細を知りたい場合は、[](info:generators) の章を参照してください。
通常のジェネレータでは、`await` は使用できません。すべての値は `for..of` 構造によって同期的である必要があります。
@@ -219,6 +332,23 @@ for(let value of range) {
構文はシンプルです。`function*` の前に `async` をつけます。これでジェネレートが非同期になります。
また、次のようにそれをイテレートするのに、`for await (...)` を使用します。
+=======
+Please see the chapter [](info:generators) if you'd like more details.
+
+In regular generators we can't use `await`. All values must come synchronously, as required by the `for..of` construct.
+
+What if we'd like to generate values asynchronously? From network requests, for instance.
+
+Let's switch to asynchronous generators to make it possible.
+
+## Async generators (finally)
+
+For most practical applications, when we'd like to make an object that asynchronously generates a sequence of values, we can use an asynchronous generator.
+
+The syntax is simple: prepend `function*` with `async`. That makes the generator asynchronous.
+
+And then use `for await (...)` to iterate over it, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
*!*async*/!* function* generateSequence(start, end) {
@@ -226,7 +356,11 @@ for(let value of range) {
for (let i = start; i <= end; i++) {
*!*
+<<<<<<< HEAD
// await が使えます!
+=======
+ // Wow, can use await!
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
await new Promise(resolve => setTimeout(resolve, 1000));
*/!*
@@ -239,12 +373,17 @@ for(let value of range) {
let generator = generateSequence(1, 5);
for *!*await*/!* (let value of generator) {
+<<<<<<< HEAD
alert(value); // 1, then 2, then 3, then 4, then 5 (間に遅延をはさみながら)
+=======
+ alert(value); // 1, then 2, then 3, then 4, then 5 (with delay between)
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
}
})();
```
+<<<<<<< HEAD
ジェネレータは非同期なので、その中で `await` や promise に依存するネットワークリクエストを実行したりできます。
````smart header="内部的な違い"
@@ -253,33 +392,63 @@ for(let value of range) {
非同期ジェネレータの場合、`generator.next()` メソッドは非同期であり、promise を返します。
通常のジェネレータでは、`result = generator.next()` を使用して値を取得します。非同期ジェネレータでは、次のように `await` を追加する必要があります:
+=======
+As the generator is asynchronous, we can use `await` inside it, rely on promises, perform network requests and so on.
+
+````smart header="Under-the-hood difference"
+Technically, if you're an advanced reader who remembers the details about generators, there's an internal difference.
+
+For async generators, the `generator.next()` method is asynchronous, it returns promises.
+
+In a regular generator we'd use `result = generator.next()` to get values. In an async generator, we should add `await`, like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
result = await generator.next(); // result = {value: ..., done: true/false}
```
+<<<<<<< HEAD
そういうわけで、非同期ジェネレータは `for await...of` で動作します。
+=======
+That's why async generators work with `for await...of`.
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
````
### Async iterable range
+<<<<<<< HEAD
通常のジェネレータは `Symbol.iterator` を使用することで、イテレーションコードをより短くすることができます。
それと同様に、非同期ジェネレータも `Symbol.asyncIterator` を使用することで、非同期のイテレーションを実装することができます。
例えば、1秒に1回、非同期に値を生成する `range` オブジェクトを作りたい場合、`Symbol.iterator` を非同期の `Symbol.asyncIterator` に置き換えることで実現できます:
+=======
+Regular generators can be used as `Symbol.iterator` to make the iteration code shorter.
+
+Similar to that, async generators can be used as `Symbol.asyncIterator` to implement the asynchronous iteration.
+
+For instance, we can make the `range` object generate values asynchronously, once per second, by replacing synchronous `Symbol.iterator` with asynchronous `Symbol.asyncIterator`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
let range = {
from: 1,
to: 5,
+<<<<<<< HEAD
// この行は次と同じです: [Symbol.asyncIterator]: async function*() {
+=======
+ // this line is same as [Symbol.asyncIterator]: async function*() {
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
*!*
async *[Symbol.asyncIterator]() {
*/!*
for(let value = this.from; value <= this.to; value++) {
+<<<<<<< HEAD
// 値の間に間隔を作り、なにかを待ちます
+=======
+ // make a pause between values, wait for something
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
await new Promise(resolve => setTimeout(resolve, 1000));
yield value;
@@ -296,6 +465,7 @@ let range = {
})();
```
+<<<<<<< HEAD
これで、値は繰り返し毎に1秒の遅延で来ます。
```smart
@@ -323,6 +493,35 @@ let range = {
`fetchCommits(repo)` 関数を作り、必要に応じてリクエストを行いコミットを取得します。そして、ページネーションについて考慮します。それは単純な非同期イテレーション `for await..of` です。
使い方は以下の通りです:
+=======
+Now values come with a delay of 1 second between them.
+
+```smart
+Technically, we can add both `Symbol.iterator` and `Symbol.asyncIterator` to the object, so it's both synchronously (`for..of`) and asynchronously (`for await..of`) iterable.
+
+In practice though, that would be a weird thing to do.
+```
+
+## Real-life example: paginated data
+
+So far we've seen basic examples, to gain understanding. Now let's review a real-life use case.
+
+There are many online services that deliver paginated data. For instance, when we need a list of users, a request returns a pre-defined count (e.g. 100 users) - "one page", and provides a URL to the next page.
+
+This pattern is very common. It's not about users, but just about anything.
+
+For instance, GitHub allows us to retrieve commits in the same, paginated fashion:
+
+- We should make a request to `fetch` in the form `https://api.github.com/repos//commits`.
+- It responds with a JSON of 30 commits, and also provides a link to the next page in the `Link` header.
+- Then we can use that link for the next request, to get more commits, and so on.
+
+For our code, we'd like to have a simpler way to get commits.
+
+Let's make a function `fetchCommits(repo)` that gets commits for us, making requests whenever needed. And let it care about all pagination stuff. For us it'll be a simple async iteration `for await..of`.
+
+So the usage will be like this:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
for await (let commit of fetchCommits("username/repository")) {
@@ -330,7 +529,11 @@ for await (let commit of fetchCommits("username/repository")) {
}
```
+<<<<<<< HEAD
これがその関数で、非同期ジェネレータで実装しています:
+=======
+Here's such function, implemented as async generator:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
async function* fetchCommits(repo) {
@@ -338,6 +541,7 @@ async function* fetchCommits(repo) {
while (url) {
const response = await fetch(url, { // (1)
+<<<<<<< HEAD
headers: {'User-Agent': 'Our script'}, // github は user-agent ヘッダを要求します
});
@@ -350,12 +554,27 @@ async function* fetchCommits(repo) {
url = nextPage;
for(let commit of body) { // (4) ページが終わるまで1つずつ yield commits
+=======
+ headers: {'User-Agent': 'Our script'}, // github needs any user-agent header
+ });
+
+ const body = await response.json(); // (2) response is JSON (array of commits)
+
+ // (3) the URL of the next page is in the headers, extract it
+ let nextPage = response.headers.get('Link').match(/<(.*?)>; rel="next"/);
+ nextPage = nextPage?.[1];
+
+ url = nextPage;
+
+ for(let commit of body) { // (4) yield commits one by one, until the page ends
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
yield commit;
}
}
}
```
+<<<<<<< HEAD
どのように動くかの説明です:
1. ブラウザの [fetch](info:fetch) メソッドを使ってコミットをダウンロードします。
@@ -368,6 +587,20 @@ async function* fetchCommits(repo) {
4. そして、受け取ったすべてのコミットを返し、それらが終了すると、次の `while(url)` イテレーションがトリガーされ、もう1つ要求を行います。
使用例 (コンソールにコミット者を表示します):
+=======
+More explanations about how it works:
+
+1. We use the browser [fetch](info:fetch) method to download the commits.
+
+ - The initial URL is `https://api.github.com/repos//commits`, and the next page will be in the `Link` header of the response.
+ - The `fetch` method allows us to supply authorization and other headers if needed -- here GitHub requires `User-Agent`.
+2. The commits are returned in JSON format.
+3. We should get the next page URL from the `Link` header of the response. It has a special format, so we use a regular expression for that (we will learn this feature in [Regular expressions](info:regular-expressions)).
+ - The next page URL may look like `https://api.github.com/repositories/93253246/commits?page=2`. It's generated by GitHub itself.
+4. Then we yield the received commits one by one, and when they finish, the next `while(url)` iteration will trigger, making one more request.
+
+An example of use (shows commit authors in console):
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js run
(async () => {
@@ -385,6 +618,7 @@ async function* fetchCommits(repo) {
})();
+<<<<<<< HEAD
// 補足: 外部のサンドボックスで実行している場合、上で記述した fetchCommits 関数をここに貼り付ける必要があります。
```
@@ -414,4 +648,36 @@ async function* fetchCommits(repo) {
Web 開発では、データがチャンクごとに流れるとき、データのストリームを扱うことがよくあります。例えば、大きなファイルのダウンロードやアップロードです。
-非同期ジェネレータを使用して、このようなデータを処理することもできます。また、ブラウザなどの一部の環境では、Stream と呼ばれる別の API もあることに注目してください。これは、データを変換してあるストリームから別のストリームに渡す特別なインターフェースを提供しますす(e.g ある場所からダウンロードして、すぐに別の場所に送信する場合)。
\ No newline at end of file
+非同期ジェネレータを使用して、このようなデータを処理することもできます。また、ブラウザなどの一部の環境では、Stream と呼ばれる別の API もあることに注目してください。これは、データを変換してあるストリームから別のストリームに渡す特別なインターフェースを提供しますす(e.g ある場所からダウンロードして、すぐに別の場所に送信する場合)。
+=======
+// Note: If you are running this in an external sandbox, you'll need to paste here the function fetchCommits described above
+```
+
+That's just what we wanted.
+
+The internal mechanics of paginated requests is invisible from the outside. For us it's just an async generator that returns commits.
+
+## Summary
+
+Regular iterators and generators work fine with the data that doesn't take time to generate.
+
+When we expect the data to come asynchronously, with delays, their async counterparts can be used, and `for await..of` instead of `for..of`.
+
+Syntax differences between async and regular iterators:
+
+| | Iterable | Async Iterable |
+|-------|-----------|-----------------|
+| Method to provide iterator | `Symbol.iterator` | `Symbol.asyncIterator` |
+| `next()` return value is | `{value:…, done: true/false}` | `Promise` that resolves to `{value:…, done: true/false}` |
+
+Syntax differences between async and regular generators:
+
+| | Generators | Async generators |
+|-------|-----------|-----------------|
+| Declaration | `function*` | `async function*` |
+| `next()` return value is | `{value:…, done: true/false}` | `Promise` that resolves to `{value:…, done: true/false}` |
+
+In web-development we often meet streams of data, when it flows chunk-by-chunk. For instance, downloading or uploading a big file.
+
+We can use async generators to process such data. It's also noteworthy that in some environments, like in browsers, there's also another API called Streams, that provides special interfaces to work with such streams, to transform the data and to pass it from one stream to another (e.g. download from one place and immediately send elsewhere).
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/12-generators-iterators/2-async-iterators-generators/head.html b/1-js/12-generators-iterators/2-async-iterators-generators/head.html
index 74d66a8b8c..b9405d9996 100644
--- a/1-js/12-generators-iterators/2-async-iterators-generators/head.html
+++ b/1-js/12-generators-iterators/2-async-iterators-generators/head.html
@@ -11,7 +11,11 @@
// the URL of the next page is in the headers, extract it
let nextPage = response.headers.get('Link').match(/<(.*?)>; rel="next"/);
+<<<<<<< HEAD
nextPage = nextPage && nextPage[1];
+=======
+ nextPage = nextPage?.[1];
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
url = nextPage;
diff --git a/1-js/12-generators-iterators/index.md b/1-js/12-generators-iterators/index.md
index 9a6bab7c9f..bb1331ca90 100644
--- a/1-js/12-generators-iterators/index.md
+++ b/1-js/12-generators-iterators/index.md
@@ -1,2 +1,6 @@
+<<<<<<< HEAD
# ジェネレータ, 高度なイテレーション
+=======
+# Generators, advanced iteration
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
diff --git a/1-js/13-modules/01-modules-intro/article.md b/1-js/13-modules/01-modules-intro/article.md
index a240dd1227..0ed3aaf03f 100644
--- a/1-js/13-modules/01-modules-intro/article.md
+++ b/1-js/13-modules/01-modules-intro/article.md
@@ -1,4 +1,5 @@
+<<<<<<< HEAD
# モジュール, 導入
アプリケーションが大きくなるにつれ、それを複数のファイルに分割したくなります。いわゆる 'モジュール' です。通常、モジュールはクラスや便利な関数のライブラリを含みます。
@@ -27,6 +28,36 @@
- `import` は他のモジュールから機能をインポートできるようにします。
例えば、関数をエクスポートしているファイル `sayHi.js` があります:
+=======
+# Modules, introduction
+
+As our application grows bigger, we want to split it into multiple files, so called "modules". A module may contain a class or a library of functions for a specific purpose.
+
+For a long time, JavaScript existed without a language-level module syntax. That wasn't a problem, because initially scripts were small and simple, so there was no need.
+
+But eventually scripts became more and more complex, so the community invented a variety of ways to organize code into modules, special libraries to load modules on demand.
+
+To name some (for historical reasons):
+
+- [AMD](https://en.wikipedia.org/wiki/Asynchronous_module_definition) -- one of the most ancient module systems, initially implemented by the library [require.js](https://requirejs.org/).
+- [CommonJS](https://wiki.commonjs.org/wiki/Modules/1.1) -- the module system created for Node.js server.
+- [UMD](https://github.com/umdjs/umd) -- one more module system, suggested as a universal one, compatible with AMD and CommonJS.
+
+Now these all slowly became a part of history, but we still can find them in old scripts.
+
+The language-level module system appeared in the standard in 2015, gradually evolved since then, and is now supported by all major browsers and in Node.js. So we'll study the modern JavaScript modules from now on.
+
+## What is a module?
+
+A module is just a file. One script is one module. As simple as that.
+
+Modules can load each other and use special directives `export` and `import` to interchange functionality, call functions of one module from another one:
+
+- `export` keyword labels variables and functions that should be accessible from outside the current module.
+- `import` allows the import of functionality from other modules.
+
+For instance, if we have a file `sayHi.js` exporting a function:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 sayHi.js
@@ -35,7 +66,11 @@ export function sayHi(user) {
}
```
+<<<<<<< HEAD
...そして、別のファイルでそれをインポートして使います。:
+=======
+...Then another file may import and use it:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 main.js
@@ -45,6 +80,7 @@ alert(sayHi); // function...
sayHi('John'); // Hello, John!
```
+<<<<<<< HEAD
`import` ディレクティブは現在のファイルからの相対パス `./sayHi.js` のモジュールを読み込み、エクスポートされた関数 `sayHi` を対応する変数に割り当てます。
ブラウザで例を実行してみましょう。
@@ -70,6 +106,33 @@ sayHi('John'); // Hello, John!
### 常に "use strict"
モジュールは常に `use strict` です。E.g. 未宣言変数への代入はエラーになります。
+=======
+The `import` directive loads the module by path `./sayHi.js` relative to the current file, and assigns exported function `sayHi` to the corresponding variable.
+
+Let's run the example in-browser.
+
+As modules support special keywords and features, we must tell the browser that a script should be treated as a module, by using the attribute `
```
+<<<<<<< HEAD
### モジュールレベルのスコープ
各モジュールには独自の最上位のスコープがあります。つまり、モジュール内の最上位の変数や関数は他のスクリプトからは見えません。
@@ -103,6 +167,34 @@ sayHi('John'); // Hello, John!
```html run
@@ -114,6 +206,7 @@ sayHi('John'); // Hello, John!
```
```smart
+<<<<<<< HEAD
ブラウザでは、e.g. `window.user = "John"` のように、変数を明示的に `window` プロパティに割り当てることで、ウィンドウレベルのグローバルな変数を作ることができます。
以降、`type="module"` の有無に関わらず、すべてのスクリプトはそれが参照できます。
@@ -130,6 +223,24 @@ sayHi('John'); // Hello, John!
いくつか例を見てみましょう。
まず、メッセージを表示すると言ったような、副作用をもたらすモジュールコードを実行する場合、複数回インポートしてもトリガされるのは1度だけです(初回)。:
+=======
+In the browser, we can make a variable window-level global by explicitly assigning it to a `window` property, e.g. `window.user = "John"`.
+
+Then all scripts will see it, both with `type="module"` and without it.
+
+That said, making such global variables is frowned upon. Please try to avoid them.
+```
+
+### A module code is evaluated only the first time when imported
+
+If the same module is imported into multiple other modules, its code is executed only once, upon the first import. Then its exports are given to all further importers.
+
+The one-time evaluation has important consequences, that we should be aware of.
+
+Let's see a couple of examples.
+
+First, if executing a module code brings side-effects, like showing a message, then importing it multiple times will trigger it only once -- the first time:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 alert.js
@@ -137,12 +248,17 @@ alert("Module is evaluated!");
```
```js
+<<<<<<< HEAD
// 別のファイルから同じモジュールをインポート
+=======
+// Import the same module from different files
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
// 📁 1.js
import `./alert.js`; // Module is evaluated!
// 📁 2.js
+<<<<<<< HEAD
import `./alert.js`; // (nothing)
```
@@ -153,6 +269,18 @@ import `./alert.js`; // (nothing)
より高度な例を考えてみましょう。
モジュールがオブジェクトをエクスポートするとしましょう:
+=======
+import `./alert.js`; // (shows nothing)
+```
+
+The second import shows nothing, because the module has already been evaluated.
+
+There's a rule: top-level module code should be used for initialization, creation of module-specific internal data structures. If we need to make something callable multiple times - we should export it as a function, like we did with `sayHi` above.
+
+Now, let's consider a deeper example.
+
+Let's say, a module exports an object:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 admin.js
@@ -161,9 +289,15 @@ export let admin = {
};
```
+<<<<<<< HEAD
このモジュールが複数のファイルからインポートされた場合、モジュールは初回にだけ評価され、`admin` オブジェクトが生成され、その後このモジュールをインポートするすべてのモジュールに渡されます。
すべてのインポータは正確に1つの `admin` オブジェクトを取得することになります。:
+=======
+If this module is imported from multiple files, the module is only evaluated the first time, `admin` object is created, and then passed to all further importers.
+
+All importers get exactly the one and only `admin` object:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 1.js
@@ -175,6 +309,7 @@ import {admin} from './admin.js';
alert(admin.name); // Pete
*!*
+<<<<<<< HEAD
// 1.js と 2.js 同じオブジェクトをインポートしました
// 1.js で行われた変更は 2.js でも見えます
*/!*
@@ -194,6 +329,27 @@ alert(admin.name); // Pete
3. 以降のインポートでは、そのモジュールを使用します。
例えば、`admin.js` モジュールは特定の機能(例. 認証など)を提供するかもしれませんが、外部から `admin` オブジェクトにクレデンシャル情報が来ることを期待します。:
+=======
+// Both 1.js and 2.js reference the same admin object
+// Changes made in 1.js are visible in 2.js
+*/!*
+```
+
+As you can see, when `1.js` changes the `name` property in the imported `admin`, then `2.js` can see the new `admin.name`.
+
+That's exactly because the module is executed only once. Exports are generated, and then they are shared between importers, so if something changes the `admin` object, other importers will see that.
+
+**Such behavior is actually very convenient, because it allows us to *configure* modules.**
+
+In other words, a module can provide a generic functionality that needs a setup. E.g. authentication needs credentials. Then it can export a configuration object expecting the outer code to assign to it.
+
+Here's the classical pattern:
+1. A module exports some means of configuration, e.g. a configuration object.
+2. On the first import we initialize it, write to its properties. The top-level application script may do that.
+3. Further imports use the module.
+
+For instance, the `admin.js` module may provide certain functionality (e.g. authentication), but expect the credentials to come into the `config` object from outside:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 admin.js
@@ -204,9 +360,15 @@ export function sayHi() {
}
```
+<<<<<<< HEAD
ここで、`admin.js` は `config` オブジェクトをエクスポートします(初期は空ですが、デフォルトプロパティもある場合もあります)。
次に `init.js` 、我々のアプリの最初のスクリプトで、`config` をインポートし、`config.user` を設定します:
+=======
+Here, `admin.js` exports the `config` object (initially empty, but may have default properties too).
+
+Then in `init.js`, the first script of our app, we import `config` from it and set `config.user`:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 init.js
@@ -214,9 +376,15 @@ import {config} from './admin.js';
config.user = "Pete";
```
+<<<<<<< HEAD
...これでモジュール `admin.js` は構成されました。
以降のインポートはこれを呼び出すことができ、現在のユーザが正しく表示されます:
+=======
+...Now the module `admin.js` is configured.
+
+Further importers can call it, and it correctly shows the current user:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```js
// 📁 another.js
@@ -228,6 +396,7 @@ sayHi(); // Ready to serve, *!*Pete*/!*!
### import.meta
+<<<<<<< HEAD
オブジェクト `import.meta` は現在のモジュールに関する情報を含んでいます。
この内容は環境に依存します。ブラウザでは、スクリプトの url、HTML 内であれば現在のウェブページの url を含んでいます。:
@@ -246,6 +415,26 @@ sayHi(); // Ready to serve, *!*Pete*/!*!
モジュールでは、最上位の `this` は undefined です。
`this` がグローバルオブジェクトである非モジュールスクリプトとの比較です:。
+=======
+The object `import.meta` contains the information about the current module.
+
+Its content depends on the environment. In the browser, it contains the URL of the script, or a current webpage URL if inside HTML:
+
+```html run height=0
+
+```
+
+### 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.
+
+Compare it to non-module scripts, where `this` is a global object:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```html run height=0
```
+<<<<<<< HEAD
## ブラウザ固有の特徴
通常のスクリプトと比べて、`type="module"` を持つスクリプトには、ブラウザ固有の違いもいくつかあります。
@@ -275,10 +465,31 @@ sayHi(); // Ready to serve, *!*Pete*/!*!
副作用として、モジュールスクリプトは常にその下の HTML 要素が見えます。
例:
+=======
+## Browser-specific features
+
+There are also several browser-specific differences of scripts with `type="module"` compared to regular ones.
+
+You may want to skip this section for now if you're reading for the first time, or if you don't use JavaScript in a browser.
+
+### Module scripts are deferred
+
+Module scripts are *always* deferred, same effect as `defer` attribute (described in the chapter [](info:script-async-defer)), for both external and inline scripts.
+
+In other words:
+- downloading external module scripts `
+
+Compare to regular script below:
+
+
```
+<<<<<<< HEAD
注意: 実際には1つ目のスクリプトの前に2つ目のスクリプトが動作します! なので、最初に `undefined` が表示され、その後 `object` が表示されます。
これは、モジュールが遅延されているためです。通常のスクリプトはすぐに実行するので、最初に出力されます。
@@ -317,6 +543,29 @@ sayHi(); // Ready to serve, *!*Pete*/!*!
```html
+=======
+Please note: the second script actually runs before the first! So we'll see `undefined` first, and then `object`.
+
+That's because modules are deferred, so we wait for the document to be processed. The regular script runs immediately, so we see its output first.
+
+When using modules, we should be aware that the HTML page shows up as it loads, and JavaScript modules run after that, so the user may see the page before the JavaScript application is ready. Some functionality may not work yet. We should put "loading indicators", or otherwise ensure that the visitor won't be confused by that.
+
+### Async works on inline scripts
+
+For non-module scripts, the `async` attribute only works on external scripts. Async scripts run immediately when ready, independently of other scripts or the HTML document.
+
+For module scripts, it works on inline scripts as well.
+
+For example, the inline script below has `async`, so it doesn't wait for anything.
+
+It performs the import (fetches `./analytics.js`) and runs when ready, even if the HTML document is not finished yet, or if other scripts are still pending.
+
+That's good for functionality that doesn't depend on anything, like counters, ads, document-level event listeners.
+
+```html
+
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
+<<<<<<< HEAD
### 外部スクリプト
外部モジュールスクリプトには、2つの大きな違いがあります。:
@@ -331,10 +581,20 @@ sayHi(); // Ready to serve, *!*Pete*/!*!
1. 同じ `src` の外部スクリプトは一度だけ実行されます:
```html
+=======
+### External scripts
+
+External scripts that have `type="module"` are different in two aspects:
+
+1. External scripts with the same `src` run only once:
+ ```html
+
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```
+<<<<<<< HEAD
2. 別のドメインから取得された外部スクリプトは[CORS](mdn:Web/HTTP/CORS) ヘッダを必要とします。言い換えると、モジュールスクリプトが別のドメインから取得された場合、リモートサーバはその取得が許可されていることを示すために、ヘッダ `Access-Control-Allow-Origin: *` (`*` の代わりに取得するドメインを指定する場合もあります)を提供しなければなりません。
```html
@@ -359,6 +619,32 @@ Node.js やバンドルツールのような特定の環境では、モジュー
### 互換性, "nomodule"
古いブラウザは `type="module"` を理解しません。未知のタイプのスクリプトは単に無視されます。それらには、`nomodule` 属性を使って、フォールバックを提供することが可能です。:
+=======
+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
+
+
+
+ ```
+
+ That ensures better security by default.
+
+### No "bare" modules allowed
+
+In the browser, `import` must get either a relative or absolute URL. Modules without any path are called "bare" modules. Such modules are not allowed in `import`.
+
+For instance, this `import` is invalid:
+```js
+import {sayHi} from 'sayHi'; // Error, "bare" module
+// the module must have a path, e.g. './sayHi.js' or wherever the module is
+```
+
+Certain environments, like Node.js or bundle tools allow bare modules, without any path, as they have their own ways for finding modules and hooks to fine-tune them. But browsers do not support bare modules yet.
+
+### Compatibility, "nomodule"
+
+Old browsers do not understand `type="module"`. Scripts of an unknown type are just ignored. For them, it's possible to provide a fallback using the `nomodule` attribute:
+>>>>>>> 540d753e90789205fc6e75c502f68382c87dea9b
```html run
@@ -416,3 +703,55 @@ Node.js やバンドルツールのような特定の環境では、モジュー
プロダクション環境では多くの場合、パフォーマンスや他の理由で、モジュールを1つにまとめるために [Webpack](https://webpack.js.org) などのバンドラを使用します。
次の章ではより多くのモジュールの例と、どのようにエクスポート/インポートされるかを見ていきます。
+=======
+ alert("Modern browsers know both type=module and nomodule, so skip this")
+ alert("Old browsers ignore script with unknown type=module, but execute this.");
+
+```
+
+## 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.
+
+One of the benefits of using bundlers -- they give more control over how modules are resolved, allowing bare modules and much more, like CSS/HTML modules.
+
+Build tools do the following:
+
+1. Take a "main" module, the one intended to be put in `
+```
+
+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 `
+