Merge pull request #4 from javascript-tutorial/master
Updating Repo 27-01-2020
2
.gitattributes
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
* text=auto eol=lf
|
||||
*.svg binary
|
|
@ -1,34 +1,34 @@
|
|||
# An Introduction to JavaScript
|
||||
|
||||
Let's see what's so special about JavaScript, what we can achieve with it and which other technologies play well with it.
|
||||
Let's see what's so special about JavaScript, what we can achieve with it, and which other technologies play well with it.
|
||||
|
||||
## What is JavaScript?
|
||||
|
||||
*JavaScript* was initially created to *"make webpages alive"*.
|
||||
*JavaScript* was initially created to *"make web pages alive"*.
|
||||
|
||||
The programs in this language are called *scripts*. They can be written right in the HTML and execute automatically as the page loads.
|
||||
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 a plain text. They don't need a special preparation or a compilation to run.
|
||||
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](http://en.wikipedia.org/wiki/Java).
|
||||
In this aspect, JavaScript is very different from another language called [Java](https://en.wikipedia.org/wiki/Java_(programming_language)).
|
||||
|
||||
```smart header="Why <u>Java</u>Script?"
|
||||
When JavaScript was created, it initially had another name: "LiveScript". But Java language was very popular at that time, so it was decided that positioning a new language as a "younger brother" of Java would help.
|
||||
```smart header="Why is it called <u>Java</u>Script?"
|
||||
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.
|
||||
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.
|
||||
```
|
||||
|
||||
At present, JavaScript can execute not only in the browser, but also on the server, or actually on any device where there exists a special program called [the JavaScript engine](https://en.wikipedia.org/wiki/JavaScript_engine).
|
||||
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 it's also called a "JavaScript virtual machine".
|
||||
The browser has an embedded engine sometimes called a "JavaScript virtual machine".
|
||||
|
||||
Different engines have different "codenames", for example:
|
||||
Different engines have different "codenames". For example:
|
||||
|
||||
- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome and Opera.
|
||||
- [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- in Firefox.
|
||||
- ...There are other codenames like "Trident", "Chakra" for different versions of IE, "ChakraCore" for Microsoft Edge, "Nitro" and "SquirrelFish" for Safari etc.
|
||||
- ...There are other codenames like "Trident" and "Chakra" for different versions of IE, "ChakraCore" for Microsoft Edge, "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 and Opera.
|
||||
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 and Opera.
|
||||
|
||||
```smart header="How do engines work?"
|
||||
|
||||
|
@ -38,16 +38,16 @@ Engines are complicated. But the basics are easy.
|
|||
2. Then it converts ("compiles") the script to the machine language.
|
||||
3. And then the machine code runs, pretty fast.
|
||||
|
||||
The engine applies optimizations on every stage of the process. It even watches the compiled script as it runs, analyzes the data that flows through it and applies optimizations to the machine code based on that knowledge. At the end, scripts are quite 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.
|
||||
```
|
||||
|
||||
## What can in-browser JavaScript do?
|
||||
|
||||
The modern JavaScript is a "safe" programming language. It does not provide low-level access to memory or CPU, because it was initially created for browsers which do not require it.
|
||||
Modern JavaScript is a "safe" programming language. It does not provide low-level access to memory or CPU, because it was initially created for browsers which do not require it.
|
||||
|
||||
The capabilities greatly depend on the environment that runs JavaScript. For instance, [Node.JS](https://wikipedia.org/wiki/Node.js) supports functions that allow JavaScript to read/write arbitrary files, perform network requests etc.
|
||||
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.
|
||||
In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver.
|
||||
|
||||
For instance, in-browser JavaScript is able to:
|
||||
|
||||
|
@ -61,7 +61,7 @@ For instance, in-browser JavaScript is able to:
|
|||
|
||||
JavaScript's abilities in the browser are limited for the sake of the user's safety. The aim is to prevent an evil webpage from accessing private information or harming the user's data.
|
||||
|
||||
The examples of such restrictions are:
|
||||
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 system functions.
|
||||
|
||||
|
@ -70,14 +70,14 @@ The examples of such restrictions are:
|
|||
There are ways to interact with 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 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 contain a special JavaScript code that handles data exchange.
|
||||
This is called the "Same Origin Policy". To work around that, *both pages* must agree for data exchange and contain a special JavaScript code that handles it. We'll cover that in the tutorial.
|
||||
|
||||
The limitation is again for user's safety. A page from `http://anysite.com` which a user has opened must not be able to access another browser tab with the URL `http://gmail.com` and steal information from there.
|
||||
- JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that's safety limitations.
|
||||
This limitation is, again, for the user's safety. A page from `http://anysite.com` which a user has opened must not be able to access another browser tab with the URL `http://gmail.com` and steal information from there.
|
||||
- JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that's a safety limitation.
|
||||
|
||||

|
||||

|
||||
|
||||
Such limits do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow installing plugin/extensions which may get extended permissions.
|
||||
Such limits do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugin/extensions which may ask for extended permissions.
|
||||
|
||||
## What makes JavaScript unique?
|
||||
|
||||
|
@ -85,16 +85,14 @@ There are at least *three* great things about JavaScript:
|
|||
|
||||
```compare
|
||||
+ Full integration with HTML/CSS.
|
||||
+ Simple things done simply.
|
||||
+ Supported by all major browsers and enabled by default.
|
||||
+ Simple things are done simply.
|
||||
+ Support by all major browsers and enabled by default.
|
||||
```
|
||||
JavaScript is the only browser technology that combines these three things.
|
||||
|
||||
Combined, these three things exist only in JavaScript and no other browser technology.
|
||||
|
||||
That's what makes JavaScript unique. That's why it's the most widespread tool to create browser interfaces.
|
||||
|
||||
While planning to learn a new technology, it's beneficial to check its perspectives. So let's move on to the modern trends that include new languages and browser abilities.
|
||||
That's what makes JavaScript unique. That's why it's the most widespread tool for creating browser interfaces.
|
||||
|
||||
That said, JavaScript also allows to create servers, mobile applications, etc.
|
||||
|
||||
## Languages "over" JavaScript
|
||||
|
||||
|
@ -104,18 +102,19 @@ That's to be expected, because projects and requirements are different for every
|
|||
|
||||
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 autoconverting it "under the hood".
|
||||
Modern tools make the transpilation very fast and transparent, actually allowing developers to code in another language and auto-converting it "under the hood".
|
||||
|
||||
Examples of such languages:
|
||||
|
||||
- [CoffeeScript](http://coffeescript.org/) is a "syntactic sugar" for JavaScript, it introduces shorter syntax, allowing to write more precise and clear code. Usually Ruby devs like it.
|
||||
- [TypeScript](http://www.typescriptlang.org/) is concentrated on adding "strict data typing", to simplify development and support of complex systems. It is developed by Microsoft.
|
||||
- [Dart](https://www.dartlang.org/) is a standalone language that has its own engine that runs in non-browser environments (like mobile apps). It was initially offered by Google as a replacement for JavaScript, but as of now, browsers require it to be transpiled to JavaScript just like the ones above.
|
||||
- [CoffeeScript](http://coffeescript.org/) is a "syntactic sugar" for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it.
|
||||
- [TypeScript](http://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](http://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.
|
||||
|
||||
There are more. Of course even if we use one of those languages, we should also know JavaScript, to really understand what we're doing.
|
||||
There are more. Of course, even if we use one of 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 now it is used in many other environments as well.
|
||||
- At this moment, JavaScript has a unique position as the most widely-adopted browser language with full integration with HTML/CSS.
|
||||
- JavaScript was initially created as a browser-only language, but is now used in many other environments as well.
|
||||
- Today, JavaScript has a unique position as the most widely-adopted browser language with full integration 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.
|
||||
|
|
Before Width: | Height: | Size: 35 KiB |
1
1-js/01-getting-started/1-intro/limitations.svg
Normal file
After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 87 KiB |
|
@ -1,56 +0,0 @@
|
|||
# Code editors
|
||||
|
||||
A code editor is the place where programmers spend most of their time.
|
||||
|
||||
There are two archetypes: IDE and lightweight editors. Many people feel comfortable choosing one tool of each type.
|
||||
|
||||
## IDE
|
||||
|
||||
The term [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) (Integrated Development Environment) means a powerful editor with many features that usually operates on a "whole project". As the name suggests, that's not just an editor, but a full-scale "development environment".
|
||||
|
||||
An IDE loads the project (can be many files), allows navigation between files, provides autocompletion based on the whole project (not just the open file), integrates with a version management system (like [git](https://git-scm.com/)), a testing environment and other "project-level" stuff.
|
||||
|
||||
If you haven't considered selecting an IDE yet, look at the following variants:
|
||||
|
||||
- [WebStorm](http://www.jetbrains.com/webstorm/) for frontend development and other editors of the same company if you need additional languages.
|
||||
- Visual Studio is fine if you're a .NET developer, and a free version is available ([Visual Studio Community](https://www.visualstudio.com/vs/community/))
|
||||
- [Netbeans](http://netbeans.org/).
|
||||
|
||||
All of the IDEs except Visual Studio are available on Windows, MacOs and Linux. Visual Studio doesn't work on Linux.
|
||||
|
||||
Most 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 instantly open and edit a file.
|
||||
|
||||
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.
|
||||
|
||||
The following options deserve your attention:
|
||||
|
||||
- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free).
|
||||
- [Atom](https://atom.io/) (cross-platform, free).
|
||||
- [Sublime Text](http://www.sublimetext.com) (cross-platform, shareware).
|
||||
- [Notepad++](https://notepad-plus-plus.org/) (Windows, free).
|
||||
- [Vim](http://www.vim.org/) and [Emacs](https://www.gnu.org/software/emacs/) are also cool, if you know how to use them.
|
||||
|
||||
## My favorites
|
||||
|
||||
The personal preference of the author is to have both an IDE for projects and a lightweight editor for quick and easy file editing.
|
||||
|
||||
I'm using:
|
||||
|
||||
- [WebStorm](http://www.jetbrains.com/webstorm/) for JS, and if there is one more language in the project, then I switch to one of the other Jetbrains offerings listed above.
|
||||
- As a lightweight editor -- [Sublime Text](http://www.sublimetext.com) or [Atom](https://atom.io/).
|
||||
|
||||
## Let's not argue
|
||||
|
||||
The editors in the lists above are those that either I or my friends who 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, personal preferences.
|
42
1-js/01-getting-started/2-manuals-specifications/article.md
Normal file
|
@ -0,0 +1,42 @@
|
|||
|
||||
# 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 sources.
|
||||
|
||||
## 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. In-between these releases, the latest specification draft is at <https://tc39.es/ecma262/>.
|
||||
|
||||
To read about new bleeding-edge features, including those that are "almost standard" (so-called "stage 3"), see proposals at <https://github.com/tc39/proposals>.
|
||||
|
||||
Also, if you're in developing for the browser, then there are other specs covered in the [second part](info:browser-environment) of the tutorial.
|
||||
|
||||
## Manuals
|
||||
|
||||
- **MDN (Mozilla) JavaScript Reference** is a manual with examples and other information. It's great to get in-depth information about individual language functions, methods etc.
|
||||
|
||||
One can find it at <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference>.
|
||||
|
||||
Although, it's often best to use an internet search instead. Just use "MDN [term]" in the query, e.g. <https://google.com/search?q=MDN+parseInt> to search for `parseInt` function.
|
||||
|
||||
|
||||
- **MSDN** – Microsoft manual with a lot of information, including JavaScript (often referred to as JScript). If one needs something specific to Internet Explorer, better go there: <http://msdn.microsoft.com/>.
|
||||
|
||||
Also, we can use an internet search with phrases such as "RegExp MSDN" or "RegExp MSDN jscript".
|
||||
|
||||
## Compatibility tables
|
||||
|
||||
JavaScript is a developing language, new features get added regularly.
|
||||
|
||||
To see their support among browser-based and other engines, see:
|
||||
|
||||
- <http://caniuse.com> - per-feature tables of support, e.g. to see which engines support modern cryptography functions: <http://caniuse.com/#feat=cryptography>.
|
||||
- <https://kangax.github.io/compat-table> - 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.
|
46
1-js/01-getting-started/3-code-editors/article.md
Normal file
|
@ -0,0 +1,46 @@
|
|||
# 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](http://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.
|
||||
|
||||
The following options deserve your attention:
|
||||
|
||||
- [Atom](https://atom.io/) (cross-platform, free).
|
||||
- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free).
|
||||
- [Sublime Text](http://www.sublimetext.com) (cross-platform, shareware).
|
||||
- [Notepad++](https://notepad-plus-plus.org/) (Windows, free).
|
||||
- [Vim](http://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.
|
|
@ -1,58 +0,0 @@
|
|||
# Developer console
|
||||
|
||||
Code is prone to errors. You are quite likely to 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, a user doesn't see the 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, browsers have embedded "developer tools".
|
||||
|
||||
Most often 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 people have a "favorite" browser and switch to others if a problem is browser-specific.
|
||||
|
||||
Developer tools are really powerful, there are 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 and press `key:Enter` to run them (`key:Shift+Enter` to input multi-line commands).
|
||||
|
||||
Now we can see errors and that's enough for the start. We'll be back to developer tools later and cover debugging more in-depth in the chapter <info:debugging-chrome>.
|
||||
|
||||
|
||||
## 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 them (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 Preferences and go to "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 under 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.
|
Before Width: | Height: | Size: 74 KiB |
Before Width: | Height: | Size: 105 KiB |
Before Width: | Height: | Size: 285 KiB |
63
1-js/01-getting-started/4-devtools/article.md
Normal file
|
@ -0,0 +1,63 @@
|
|||
# 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 <info:debugging-chrome>.
|
||||
|
||||
```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 Preferences and go to the "Advanced" pane. There's a checkbox at the bottom:
|
||||
|
||||

|
||||
|
||||
Now `key:Cmd+Opt+C` can toggle the console. Also, note that the new top menu item named "Develop" has appeared. It has many commands and options.
|
||||
|
||||
## 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.
|
BIN
1-js/01-getting-started/4-devtools/chrome.png
Normal file
After Width: | Height: | Size: 41 KiB |
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 68 KiB |
BIN
1-js/01-getting-started/4-devtools/safari.png
Normal file
After Width: | Height: | Size: 107 KiB |
BIN
1-js/01-getting-started/4-devtools/safari@2x.png
Normal file
After Width: | Height: | Size: 266 KiB |
|
@ -1,15 +1,15 @@
|
|||
# Hello, world!
|
||||
|
||||
The tutorial that you're reading is about core JavaScript, which is platform-independent. Further on, you will learn Node.JS and other platforms that use it.
|
||||
This part of the tutorial is about core JavaScript, the language itself.
|
||||
|
||||
But, we need a working environment to run our scripts, and, just because this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`) to a minimum, so that you don't spend time on them if you plan to concentrate on another environment like Node.JS. On the other hand, browser details are explained in detail in the [next part](/ui) of the tutorial.
|
||||
But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`) to a minimum so that you don't spend time on them if you plan to concentrate on another environment (like Node.js). We'll focus on JavaScript in the browser in the [next part](/ui) of the tutorial.
|
||||
|
||||
So first, let's see how to attach a script to a webpage. For server-side environments, you can just execute it with a command like `"node my.js"` for Node.JS.
|
||||
So first, let's see how we attach a script to a webpage. For server-side environments (like Node.js), you can execute the script with a command like `"node my.js"`.
|
||||
|
||||
|
||||
## The "script" tag
|
||||
|
||||
JavaScript programs can be inserted in any part of an HTML document with the help of the `<script>` tag.
|
||||
JavaScript programs can be inserted into any part of an HTML document with the help of the `<script>` tag.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -35,25 +35,24 @@ For instance:
|
|||
```
|
||||
|
||||
```online
|
||||
You can run the example by clicking on the "Play" button in its right-top corner.
|
||||
You can run the example by clicking the "Play" button in the right-top corner of the box above.
|
||||
```
|
||||
|
||||
The `<script>` tag contains JavaScript code which is automatically executed when the browser meets the tag.
|
||||
The `<script>` tag contains JavaScript code which is automatically executed when the browser processes the tag.
|
||||
|
||||
|
||||
## The modern markup
|
||||
## Modern markup
|
||||
|
||||
The `<script>` tag has a few attributes that are rarely used nowadays, but we can find them in old code:
|
||||
The `<script>` tag has a few attributes that are rarely used nowadays but can still be found in old code:
|
||||
|
||||
The `type` attribute: <code><script <u>type</u>=...></code>
|
||||
The `type` attribute: <code><script <u>type</u>=...></code>
|
||||
: The old HTML standard, HTML4, required a script to have a `type`. Usually it was `type="text/javascript"`. It's not required anymore. Also, the modern HTML standard totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic; we'll talk about modules in another part of the tutorial.
|
||||
|
||||
: The old standard HTML4 required a script to have a type. Usually it was `type="text/javascript"`. It's not required any more. Also, the modern standard totally changed the meaning of this attribute. Now it can be used for Javascript modules. But that's an advanced topic, but we'll talk about modules later in another part of the tutorial.
|
||||
|
||||
The `language` attribute: <code><script <u>language</u>=...></code>
|
||||
: This attribute was meant to show the language of the script. As of now, this attribute makes no sense, the language is JavaScript by default. No need to use it.
|
||||
The `language` attribute: <code><script <u>language</u>=...></code>
|
||||
: This attribute was meant to show the language of the script. This attribute no longer makes sense because JavaScript is the default language. There is no need to use it.
|
||||
|
||||
Comments before and after scripts.
|
||||
: In really ancient books and guides, one may find comments inside `<script>`, like this:
|
||||
: In really ancient books and guides, you may find comments inside `<script>` tags, like this:
|
||||
|
||||
```html no-beautify
|
||||
<script type="text/javascript"><!--
|
||||
|
@ -61,24 +60,22 @@ Comments before and after scripts.
|
|||
//--></script>
|
||||
```
|
||||
|
||||
This trick isn't used in modern JavaScript. These comments were used to hide the JavaScript code from old browsers that didn't know about a `<script>` tag. Since browsers born in the last 15 years don't have this issue, this kind of comment can help you identify really old code.
|
||||
This trick isn't used in modern JavaScript. These comments hide JavaScript code from old browsers that didn't know how to process the `<script>` tag. Since browsers released in the last 15 years don't have this issue, this kind of comment can help you identify really old code.
|
||||
|
||||
|
||||
## External scripts
|
||||
|
||||
If we have a lot of JavaScript code, we can put it into a separate file.
|
||||
|
||||
The script file is attached to HTML with the `src` attribute:
|
||||
Script files are attached to HTML with the `src` attribute:
|
||||
|
||||
```html
|
||||
<script src="/path/to/script.js"></script>
|
||||
```
|
||||
|
||||
Here `/path/to/script.js` is an absolute path to the file with the script (from the site root).
|
||||
Here, `/path/to/script.js` is an absolute path to the script from the site root. One can also provide a relative path from the current page. For instance, `src="script.js"` would mean a file `"script.js"` in the current folder.
|
||||
|
||||
It is also possible to provide a path relative to the current page. For instance, `src="script.js"` would mean a file `"script.js"` in the current folder.
|
||||
|
||||
We can give a full URL as well, for instance:
|
||||
We can give a full URL as well. For instance:
|
||||
|
||||
```html
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
|
||||
|
@ -95,15 +92,15 @@ To attach several scripts, use multiple tags:
|
|||
```smart
|
||||
As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate files.
|
||||
|
||||
The benefit of a separate file is that the browser will download it and then store in its [cache](https://en.wikipedia.org/wiki/Web_cache).
|
||||
The benefit of a separate file is that the browser will download it and store it in its [cache](https://en.wikipedia.org/wiki/Web_cache).
|
||||
|
||||
After this, other pages that want the same script will take it from the cache instead of downloading it. So the file is actually downloaded only once.
|
||||
Other pages that reference the same script will take it from the cache instead of downloading it, so the file is actually downloaded only once.
|
||||
|
||||
That saves traffic and makes pages faster.
|
||||
That reduces traffic and makes pages faster.
|
||||
```
|
||||
|
||||
````warn header="If `src` is set, the script content is ignored."
|
||||
A single `<script>` tag can't have both the `src` attribute and the code inside.
|
||||
A single `<script>` tag can't have both the `src` attribute and code inside.
|
||||
|
||||
This won't work:
|
||||
|
||||
|
@ -113,7 +110,7 @@ This won't work:
|
|||
</script>
|
||||
```
|
||||
|
||||
We must choose: either it's an external `<script src="…">` or a regular `<script>` with code.
|
||||
We must choose either an external `<script src="…">` or a regular `<script>` with code.
|
||||
|
||||
The example above can be split into two scripts to work:
|
||||
|
||||
|
@ -127,9 +124,9 @@ The example above can be split into two scripts to work:
|
|||
|
||||
## Summary
|
||||
|
||||
- We can use a `<script>` tag to add JavaScript code to the page.
|
||||
- We can use a `<script>` tag to add JavaScript code to a page.
|
||||
- The `type` and `language` attributes are not required.
|
||||
- A script in an external file can be inserted with `<script src="path/to/script.js"></script>`.
|
||||
|
||||
|
||||
There is much more to learn about browser scripts and their interaction with the web-page. But let's keep in mind that this part of the tutorial is devoted to the JavaScript language, so we shouldn't distract ourselves from it. We'll be using a browser as a way to run JavaScript, which is very convenient for online reading, but yet one of many.
|
||||
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.
|
||||
|
|
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 83 KiB |
|
@ -1,22 +1,22 @@
|
|||
# Code structure
|
||||
|
||||
The first thing to study is the building blocks of the code.
|
||||
The first thing we'll study is the building blocks of code.
|
||||
|
||||
## Statements
|
||||
|
||||
Statements are syntax constructs and commands that perform actions.
|
||||
|
||||
We've already seen a statement `alert('Hello, world!')`, which shows the message.
|
||||
We've already seen a statement, `alert('Hello, world!')`, which shows the message "Hello, world!".
|
||||
|
||||
We can have as many statements in the code as we want. Another statement can be separated with a semicolon.
|
||||
We can have as many statements in our code as we want. Statements can be separated with a semicolon.
|
||||
|
||||
For example, here we split the message into two:
|
||||
For example, here we split "Hello World" into two alerts:
|
||||
|
||||
```js run no-beautify
|
||||
alert('Hello'); alert('World');
|
||||
```
|
||||
|
||||
Usually each statement is written on a separate line -- thus the code becomes more readable:
|
||||
Usually, statements are written on separate lines to make the code more readable:
|
||||
|
||||
```js run no-beautify
|
||||
alert('Hello');
|
||||
|
@ -34,11 +34,11 @@ alert('Hello')
|
|||
alert('World')
|
||||
```
|
||||
|
||||
Here JavaScript interprets the line break as an "implicit" semicolon. That's also called an [automatic semicolon insertion](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"!**
|
||||
**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:
|
||||
There are cases when a newline does not mean a semicolon. For example:
|
||||
|
||||
```js run no-beautify
|
||||
alert(3 +
|
||||
|
@ -46,7 +46,7 @@ alert(3 +
|
|||
+ 2);
|
||||
```
|
||||
|
||||
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", no semicolon required. And in this case that works as intended.
|
||||
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 the semicolon is not required. And in this case that works as intended.
|
||||
|
||||
**But there are situations where JavaScript "fails" to assume a semicolon where it is really needed.**
|
||||
|
||||
|
@ -59,9 +59,9 @@ If you're curious to see a concrete example of such an error, check this code ou
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later, for now it does not matter. Let's just remember the result: it shows `1`, then `2`.
|
||||
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 the code: it shows `1` then `2`.
|
||||
|
||||
Now let's add an `alert` before the code and *not* finish it with a semicolon:
|
||||
Now, let's add an `alert` before the code and *not* finish it with a semicolon:
|
||||
|
||||
```js run no-beautify
|
||||
alert("There will be an error")
|
||||
|
@ -69,7 +69,7 @@ alert("There will be an error")
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
Now if we run it, only the first `alert` is shown, and then we have an error!
|
||||
Now if we run the code, only the first `alert` is shown and then we have an error!
|
||||
|
||||
But everything is fine again if we add a semicolon after `alert`:
|
||||
```js run
|
||||
|
@ -78,27 +78,27 @@ alert("All fine now");
|
|||
[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
Now we have the "All fine now" message and then `1` and `2`.
|
||||
Now we have the "All fine now" message followed by `1` and `2`.
|
||||
|
||||
|
||||
The error in the no-semicolon variant occurs because JavaScript does not imply a semicolon before square brackets `[...]`.
|
||||
The error in the no-semicolon variant occurs because JavaScript does not assume a semicolon before square brackets `[...]`.
|
||||
|
||||
So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. That's how the engine sees it:
|
||||
So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. Here's how the engine sees it:
|
||||
|
||||
```js run no-beautify
|
||||
alert("There will be an error")[1, 2].forEach(alert)
|
||||
```
|
||||
|
||||
But it should be two separate statements, not a single one. Such a merging in this case is just wrong, hence the error. There are other situations when such a thing happens.
|
||||
But it should be two separate statements, not one. Such a merging in this case is just wrong, hence the error. This can happen in other situations.
|
||||
````
|
||||
|
||||
It's recommended to put 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.
|
||||
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
|
||||
|
||||
As time goes on, the program becomes more and more complex. It becomes necessary to add *comments* which describe what happens and why.
|
||||
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 the script. They don't affect the execution, because the engine simply ignores them.
|
||||
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 `//`.**
|
||||
|
||||
|
@ -124,9 +124,9 @@ alert('Hello');
|
|||
alert('World');
|
||||
```
|
||||
|
||||
The content of comments is ignored, so if we put code inside <code>/* ... */</code> it won't execute.
|
||||
The content of comments is ignored, so if we put code inside <code>/* ... */</code>, it won't execute.
|
||||
|
||||
Sometimes it comes in handy to temporarily disable a part of code:
|
||||
Sometimes it can be handy to temporarily disable a part of code:
|
||||
|
||||
```js run
|
||||
/* Commenting out the code
|
||||
|
@ -136,7 +136,7 @@ alert('World');
|
|||
```
|
||||
|
||||
```smart header="Use hotkeys!"
|
||||
In most editors a line of code can be commented out by `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`.
|
||||
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`.
|
||||
```
|
||||
|
||||
````warn header="Nested comments are not supported!"
|
||||
|
@ -154,6 +154,6 @@ alert( 'World' );
|
|||
|
||||
Please, don't hesitate to comment your code.
|
||||
|
||||
Comments increase the overall code footprint, but that's not a problem at all. There are many tools which minify the code before publishing to the production server. They remove comments, so they don't appear in the working scripts. Therefore comments do not have any negative effects on production at all.
|
||||
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.
|
||||
|
||||
Further in the tutorial, there will be a chapter <info:coding-style> that also explains how to write better comments.
|
||||
Later in the tutorial there will be a chapter <info:code-quality> that also explains how to write better comments.
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
# The modern mode, "use strict"
|
||||
|
||||
For a long time JavaScript was evolving without compatibility issues. New features were added to the language, but the old functionality did not change.
|
||||
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 creators got stuck in the language forever.
|
||||
That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever.
|
||||
|
||||
It had been so until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most modifications are off by default. One needs to enable them explicitly with a special directive `"use strict"`.
|
||||
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most such modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`.
|
||||
|
||||
## "use strict"
|
||||
|
||||
The directive looks like a string: `"use strict"` or `'use strict'`. When it is located on the top of the script, then the whole script works the "modern" way.
|
||||
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
|
||||
For example:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
@ -19,19 +19,17 @@ For example
|
|||
...
|
||||
```
|
||||
|
||||
We will learn functions (a way to group commands) soon.
|
||||
|
||||
Looking ahead let's just note that `"use strict"` can be put at the start of a function (most kinds of functions) instead of the whole script. Then strict mode is enabled in that function only. But usually people use it for the whole script.
|
||||
We will learn functions (a way to group commands) soon. Looking ahead, let's note that `"use strict"` can be put at the beginning of the function body instead of the whole script. Doing that enables strict mode in that function only. But usually, people use it for the whole script.
|
||||
|
||||
|
||||
````warn header="Ensure that \"use strict\" is at the top"
|
||||
Please make sure that `"use strict"` is on the top of the script, otherwise the strict mode may not be enabled.
|
||||
Please make sure that `"use strict"` is at the top of your scripts, otherwise strict mode may not be enabled.
|
||||
|
||||
There is no strict mode here:
|
||||
Strict mode isn't enabled here:
|
||||
|
||||
```js no-strict
|
||||
alert("some code");
|
||||
// "use strict" below is ignored, must be on the top
|
||||
// "use strict" below is ignored--it must be at the top
|
||||
|
||||
"use strict";
|
||||
|
||||
|
@ -42,20 +40,46 @@ Only comments may appear above `"use strict"`.
|
|||
````
|
||||
|
||||
```warn header="There's no way to cancel `use strict`"
|
||||
There is no directive `"no use strict"` or alike, that would return the old behavior.
|
||||
There is no directive like `"no use strict"` that reverts the engine to old behavior.
|
||||
|
||||
Once we enter the strict mode, there's no return.
|
||||
Once we enter strict mode, there's no going back.
|
||||
```
|
||||
|
||||
## Browser console
|
||||
|
||||
For the future, when you use a browser console to test features, please note that it doesn't `use strict` by default.
|
||||
|
||||
Sometimes, when `use strict` makes a difference, you'll get incorrect results.
|
||||
|
||||
You can try to press `key:Shift+Enter` to input multiple lines, and put `use strict` on top, like this:
|
||||
|
||||
```js
|
||||
'use strict'; <Shift+Enter for a newline>
|
||||
// ...your code
|
||||
<Enter to run>
|
||||
```
|
||||
|
||||
It works in most browsers, namely Firefox and Chrome.
|
||||
|
||||
If it doesn't, the most reliable way to ensure `use strict` would be to input the code into console like this:
|
||||
|
||||
```js
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// ...your code...
|
||||
})()
|
||||
```
|
||||
|
||||
## Always "use strict"
|
||||
|
||||
The differences of `"use strict"` versus the "default" mode are still to be covered.
|
||||
We have yet to cover the differences between strict mode and the "default" mode.
|
||||
|
||||
In the next chapters, as we learn language features, we'll make notes about the differences of the strict mode. Luckily, there are not so many. And they actually make our life better.
|
||||
In the next chapters, as we learn language features, we'll note the differences between the strict and default modes. Luckily, there aren't many and they actually make our lives better.
|
||||
|
||||
At this point in time it's enough to know about it in general:
|
||||
For now, it's enough to know about it in general:
|
||||
|
||||
1. The `"use strict"` directive switches the engine to the "modern" mode, changing the behavior of some built-in features. We'll see the details as we study.
|
||||
2. The strict mode is enabled by `"use strict"` at the top. Also there are several language features like "classes" and "modules" that enable strict mode automatically.
|
||||
3. The strict mode is supported by all modern browsers.
|
||||
4. It's always recommended to start scripts with `"use strict"`. All examples in this tutorial assume so, unless (very rarely) specified otherwise.
|
||||
1. The `"use strict"` directive switches the engine to the "modern" mode, changing the behavior of some built-in features. We'll see the details later in the tutorial.
|
||||
2. Strict mode is enabled by placing `"use strict"` at the top of a script or function. Several language features, like "classes" and "modules", enable strict mode automatically.
|
||||
3. Strict mode is supported by all modern browsers.
|
||||
4. We recommended always starting scripts with `"use strict"`. All examples in this tutorial assume strict mode unless (very rarely) specified otherwise.
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
First, the variable for the name of our planet.
|
||||
## The variable for our planet
|
||||
|
||||
That's simple:
|
||||
|
||||
|
@ -8,7 +8,7 @@ let ourPlanetName = "Earth";
|
|||
|
||||
Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
|
||||
|
||||
Second, the name of the current visitor:
|
||||
## The name of the current visitor
|
||||
|
||||
```js
|
||||
let currentUserName = "John";
|
||||
|
@ -18,4 +18,4 @@ Again, we could shorten that to `userName` if we know for sure that the user is
|
|||
|
||||
Modern editors and autocomplete make long variable names easy to write. Don't save on them. A name with 3 words in it is fine.
|
||||
|
||||
And if your editor does not have proper autocompletion, get [a new one](/editors).
|
||||
And if your editor does not have proper autocompletion, get [a new one](/code-editors).
|
||||
|
|
|
@ -4,5 +4,5 @@ importance: 3
|
|||
|
||||
# Giving the right name
|
||||
|
||||
1. Create the variable with the name of our planet. How would you name such a variable?
|
||||
2. Create the variable to store the name of the current visitor. How would you name that variable?
|
||||
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?
|
||||
|
|
|
@ -2,4 +2,4 @@ We generally use upper case for constants that are "hard-coded". Or, in other wo
|
|||
|
||||
In this code, `birthday` is exactly like that. So we could use the upper case for it.
|
||||
|
||||
In contrast, `age` is evaluated in run-time. Today we have one age, a year after we'll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit "less of a constant" than `birthday`, it is calculated, so we should keep the lower case for it.
|
||||
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.
|
||||
|
|
|
@ -1,24 +1,24 @@
|
|||
# Variables
|
||||
|
||||
Most of the time, a JavaScript application needs to work with information. Here are 2 examples:
|
||||
1. An online-shop -- the information might include goods being sold and a shopping cart.
|
||||
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.
|
||||
|
||||
Variables are used to store this information.
|
||||
|
||||
## 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.
|
||||
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, we need to use the `let` keyword.
|
||||
To create a variable in JavaScript, use the `let` keyword.
|
||||
|
||||
The statement below creates (in other words: *declares* or *defines*) a variable with the name "message":
|
||||
The statement below creates (in other words: *declares*) a variable with the name "message":
|
||||
|
||||
```js
|
||||
let message;
|
||||
```
|
||||
|
||||
Now we can put some data into it by using the assignment operator `=`:
|
||||
Now, we can put some data into it by using the assignment operator `=`:
|
||||
|
||||
```js
|
||||
let message;
|
||||
|
@ -39,7 +39,7 @@ alert(message); // shows the variable content
|
|||
*/!*
|
||||
```
|
||||
|
||||
To be concise we can merge the variable declaration and assignment into a single line:
|
||||
To be concise, we can combine the variable declaration and assignment into a single line:
|
||||
|
||||
```js run
|
||||
let message = 'Hello!'; // define the variable and assign the value
|
||||
|
@ -53,7 +53,7 @@ We can also declare multiple variables in one line:
|
|||
let user = 'John', age = 25, message = 'Hello';
|
||||
```
|
||||
|
||||
That might seem shorter, but it's not recommended. For the sake of better readability, please use a single line per variable.
|
||||
That might seem shorter, but we don't recommend it. For the sake of better readability, please use a single line per variable.
|
||||
|
||||
The multiline variant is a bit longer, but easier to read:
|
||||
|
||||
|
@ -63,7 +63,7 @@ let age = 25;
|
|||
let message = 'Hello';
|
||||
```
|
||||
|
||||
Some people also write many variables like that:
|
||||
Some people also define multiple variables in this multiline style:
|
||||
```js no-beautify
|
||||
let user = 'John',
|
||||
age = 25,
|
||||
|
@ -78,19 +78,19 @@ let user = 'John'
|
|||
, message = 'Hello';
|
||||
```
|
||||
|
||||
Technically, all these variants do the same. So, it's a matter of personal taste and aesthetics.
|
||||
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`:
|
||||
In older scripts, you may also find another keyword: `var` instead of `let`:
|
||||
|
||||
```js
|
||||
*!*var*/!* message = 'Hello';
|
||||
```
|
||||
|
||||
The `var` keyword is *almost* the same as `let`. It also declares a variable, but in a slightly different, "old-school" fashion.
|
||||
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 for us yet. We'll cover them in detail later, in the chapter <info:var>.
|
||||
There are subtle differences between `let` and `var`, but they do not matter for us yet. We'll cover them in detail in the chapter <info:var>.
|
||||
````
|
||||
|
||||
## A real-life analogy
|
||||
|
@ -99,12 +99,11 @@ We can easily grasp the concept of a "variable" if we imagine it as a "box" for
|
|||
|
||||
For instance, the variable `message` can be imagined as a box labeled `"message"` with the value `"Hello!"` in it:
|
||||
|
||||

|
||||

|
||||
|
||||
We can put any value into the box.
|
||||
|
||||
Also we can change it. The value can be changed as many times as needed:
|
||||
We can put any value in the box.
|
||||
|
||||
We can also change it as many times as we want:
|
||||
```js run
|
||||
let message;
|
||||
|
||||
|
@ -117,7 +116,7 @@ alert(message);
|
|||
|
||||
When the value is changed, the old data is removed from the variable:
|
||||
|
||||

|
||||

|
||||
|
||||
We can also declare two variables and copy data from one into the other.
|
||||
|
||||
|
@ -137,28 +136,28 @@ alert(message); // Hello world!
|
|||
```
|
||||
|
||||
```smart header="Functional languages"
|
||||
It may be interesting to know that there also exist [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages that forbid changing a variable value. For example, [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/).
|
||||
It's interesting to note that there exist [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages, like [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/) that forbid changing variable values.
|
||||
|
||||
In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can't reuse the old one.
|
||||
|
||||
Though it may seem a little bit 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. Studying such a language (even if not planning to use it soon) is recommended to broaden the mind.
|
||||
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. Studying such a language (even if you're not planning to use it soon) is recommended to broaden the mind.
|
||||
```
|
||||
|
||||
## Variable naming [#variable-naming]
|
||||
|
||||
There are two limitations for a variable name in JavaScript:
|
||||
There are two limitations on variable names in JavaScript:
|
||||
|
||||
1. The name must contain only letters, digits, symbols `$` and `_`.
|
||||
1. The name must contain only letters, digits, or the symbols `$` and `_`.
|
||||
2. The first character must not be a digit.
|
||||
|
||||
Valid names, for instance:
|
||||
Examples of valid names:
|
||||
|
||||
```js
|
||||
let userName;
|
||||
let test123;
|
||||
```
|
||||
|
||||
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 starts with a capital letter: `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`.
|
||||
|
||||
What's interesting -- the dollar sign `'$'` and the underscore `'_'` can also be used in names. They are regular symbols, just like letters, without any special meaning.
|
||||
|
||||
|
@ -176,14 +175,14 @@ Examples of incorrect variable names:
|
|||
```js no-beautify
|
||||
let 1a; // cannot start with a digit
|
||||
|
||||
let my-name; // a hyphen '-' is not allowed in the name
|
||||
let my-name; // hyphens '-' aren't allowed in the name
|
||||
```
|
||||
|
||||
```smart header="Case matters"
|
||||
Variables named `apple` and `AppLE` -- are two different variables.
|
||||
Variables named `apple` and `AppLE` are two different variables.
|
||||
```
|
||||
|
||||
````smart header="Non-english letters are allowed, but not recommended"
|
||||
````smart header="Non-Latin letters are allowed, but not recommended"
|
||||
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
|
||||
|
||||
```js
|
||||
|
@ -195,9 +194,9 @@ Technically, there is no error here, such names are allowed, but there is an int
|
|||
````
|
||||
|
||||
````warn header="Reserved names"
|
||||
There is a list of reserved words, which cannot be used as variable names, because they are used by the language itself.
|
||||
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, words `let`, `class`, `return`, `function` are reserved.
|
||||
For example: `let`, `class`, `return`, and `function` are reserved.
|
||||
|
||||
The code below gives a syntax error:
|
||||
|
||||
|
@ -209,37 +208,36 @@ let return = 5; // also can't name it "return", error!
|
|||
|
||||
````warn header="An assignment without `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 `let`. This still works now if we don't put `use strict`. The behavior is kept for compatibility with old scripts.
|
||||
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.
|
||||
|
||||
```js run no-strict
|
||||
// note: no "use strict" in this example
|
||||
|
||||
num = 5; // the variable "num" is created if didn't exist
|
||||
num = 5; // the variable "num" is created if it didn't exist
|
||||
|
||||
alert(num); // 5
|
||||
```
|
||||
|
||||
That's a bad practice, it gives an error in the strict mode:
|
||||
This is a bad practice and would cause an error in strict mode:
|
||||
|
||||
```js run untrusted
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
*!*
|
||||
num = 5; // error: num is not defined
|
||||
*/!*
|
||||
```
|
||||
|
||||
````
|
||||
|
||||
## Constants
|
||||
|
||||
To declare a constant (unchanging) variable, one can use `const` instead of `let`:
|
||||
To declare a constant (unchanging) variable, use `const` instead of `let`:
|
||||
|
||||
```js
|
||||
const myBirthday = '18.04.1982';
|
||||
```
|
||||
|
||||
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do it would cause an error:
|
||||
Variables declared using `const` are called "constants". They cannot be reassigned. An attempt to do so would cause an error:
|
||||
|
||||
```js run
|
||||
const myBirthday = '18.04.1982';
|
||||
|
@ -247,7 +245,7 @@ const myBirthday = '18.04.1982';
|
|||
myBirthday = '01.01.2001'; // error, can't reassign the constant!
|
||||
```
|
||||
|
||||
When a programmer is sure that the variable should never change, they can use `const` to guarantee it, and also to clearly show that fact to everyone.
|
||||
When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and clearly communicate that fact to everyone.
|
||||
|
||||
|
||||
### Uppercase constants
|
||||
|
@ -256,7 +254,7 @@ There is a widespread practice to use constants as aliases for difficult-to-reme
|
|||
|
||||
Such constants are named using capital letters and underscores.
|
||||
|
||||
Like this:
|
||||
For instance, let's make constants for colors in so-called "web" (hexadecimal) format:
|
||||
|
||||
```js run
|
||||
const COLOR_RED = "#F00";
|
||||
|
@ -272,19 +270,19 @@ alert(color); // #FF7F00
|
|||
Benefits:
|
||||
|
||||
- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
|
||||
- It is much easier to mistype in `"#FF7F00"` than in `COLOR_ORANGE`.
|
||||
- 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 them normally? Let's make that clear.
|
||||
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 the value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red), and there are those that are *calculated* in run-time, during the execution, but do not change after the assignment.
|
||||
Being a "constant" just means that a variable's value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are *calculated* in run-time, during the execution, but do not change after their initial assignment.
|
||||
|
||||
For instance:
|
||||
```js
|
||||
const pageLoadTime = /* time taken by a webpage to load */;
|
||||
```
|
||||
|
||||
The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant, because it doesn't change after assignment.
|
||||
The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant because it doesn't change after assignment.
|
||||
|
||||
In other words, capital-named constants are only used as aliases for "hard-coded" values.
|
||||
|
||||
|
@ -292,41 +290,41 @@ In other words, capital-named constants are only used as aliases for "hard-coded
|
|||
|
||||
Talking about variables, there's one more extremely important thing.
|
||||
|
||||
Please name the variables sensibly. Take time to think if needed.
|
||||
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 quick glance at variable names can reveal which code is written by a beginner and which by an experienced developer.
|
||||
Variable naming is one of the most important and complex skills in programming. A quick 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 on modifying and extending the existing code base, rather than writing something completely separate from scratch. And when we return to the code after some time of doing something else, it's much easier to find information that is well-labeled. Or, in other words, when the variables have good names.
|
||||
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-labeled. Or, in other words, when the variables have good names.
|
||||
|
||||
Please spend some time thinking about the right name for a variable before declaring it. This will repay you a lot.
|
||||
Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.
|
||||
|
||||
Some good-to-follow rules are:
|
||||
|
||||
- Use human-readable names like `userName` or `shoppingCart`.
|
||||
- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really know what you're doing.
|
||||
- Make the name maximally descriptive and concise. Examples of bad names are `data` and `value`. Such a name says nothing. It is only ok to use them if it's exceptionally obvious from the context which data or value is meant.
|
||||
- Agree on terms within your team and in your own mind. If a site visitor is called a "user" then we should name related variables like `currentUser` or `newUser`, but not `currentVisitor` or a `newManInTown`.
|
||||
- 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 own 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 good descriptive-and-concise names in practice is not. Go for it.
|
||||
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 a new variable, tend to reuse the existing ones.
|
||||
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
|
||||
|
||||
As a result, the variable is like a box where people throw different things without changing the sticker. What is inside it now? Who knows... We need to come closer and check.
|
||||
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 a programmer saves a little bit on variable declaration, but loses ten times more on debugging the code.
|
||||
Such programmers save a little bit on variable declaration but lose ten times more on debugging.
|
||||
|
||||
An extra variable is good, not evil.
|
||||
|
||||
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 to optimize.
|
||||
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.
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
We can declare variables to store data. That can be done using `var` or `let` or `const`.
|
||||
We can declare variables to store data by using the `var`, `let`, or `const` keywords.
|
||||
|
||||
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
|
||||
- `let` -- is a modern variable declaration.
|
||||
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
|
||||
- `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.
|
||||
Variables should be named in a way that allows us to easily understand what's inside them.
|
||||
|
|
Before Width: | Height: | Size: 18 KiB |
1
1-js/02-first-steps/04-variables/variable-change.svg
Normal file
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="392" height="192" viewBox="0 0 392 192"><defs><style>@import url(https://fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic%7CPT+Mono);@font-face{font-family:'PT Mono';font-weight:700;font-style:normal;src:local('PT MonoBold'),url(/font/PTMonoBold.woff2) format('woff2'),url(/font/PTMonoBold.woff) format('woff'),url(/font/PTMonoBold.ttf) format('truetype')}</style></defs><g id="combined" fill="none" fill-rule="evenodd" stroke="none" stroke-width="1"><g id="variable-change.svg"><g id="noun_1211_cc" transform="translate(52 -5)"><path id="Shape" fill="#E8C48F" d="M25 94.196h112.558v42.95c0 .373-.079.862-.279 1.294-.2.433-16.574 35.56-16.574 35.56v-54.36l16.854-25.444L156 66H43.44L25 94.196zM25 123V95l-15 28"/><g id="Rectangle-5-+-"World!"" transform="translate(0 57)"><path id="Rectangle-5" fill="#FFF9EB" stroke="#8A704D" stroke-width="2" d="M18.861 1.809L2 17.533l53.14 56.986L72 58.794 18.861 1.81z"/><text id=""World!"" fill="#8A704D" font-family="OpenSans-Bold, Open Sans" font-size="14" font-weight="bold" transform="rotate(47 40.083 39.762)"><tspan x="10.591" y="46.262">"World!"</tspan></text></g><g id="Rectangle-5-+-"World!"-2" transform="rotate(-67 96.824 -33.912)"><path id="Rectangle-5" fill="#FFF9EB" stroke="#8A704D" stroke-width="2" d="M18.861 1.809L2 17.533l53.14 56.986L72 58.794 18.861 1.81z"/><text id=""Hello!"" fill="#8A704D" font-family="OpenSans-Bold, Open Sans" font-size="14" font-weight="bold" transform="rotate(47 40.083 39.762)"><tspan x="10.591" y="46.262">"Hello!"</tspan></text></g><path id="Shape" fill="#E8C48F" d="M8 125v54.73c0 3.42 1.484 5.27 4.387 5.27h100.086c3.122 0 5.527-2.548 5.527-3.476V125H8z"/></g><text id="message" fill="#FFF" font-family="OpenSans-Bold, Open Sans" font-size="18" font-weight="bold"><tspan x="77" y="157">message</tspan></text><path id="Fill-54" fill="#E8C48F" d="M58.112 51.808S47.657 40.623 40.719 36.155l-.505 5.542a76.036 76.036 0 00-33.769 4.595l4.169 11.032a64.248 64.248 0 0128.531-3.882l-.505 5.542c5.581-3.329 19.472-7.176 19.472-7.176" transform="rotate(11 32.278 47.57)"/><path id="Fill-54" fill="#E8C48F" d="M287.797 28.186s-10.454-11.185-17.393-15.653l-.505 5.541a76.036 76.036 0 00-33.769 4.596l4.169 11.032a64.248 64.248 0 0128.531-3.882l-.504 5.541c5.58-3.328 19.47-7.175 19.47-7.175" transform="rotate(2 261.964 23.947)"/><g id="noun_48910_cc" transform="translate(298 5)"><path id="Shape" d="M50.983 6H36.016C35.456 6 35 6.626 35 7.395V12h17V7.395C52 6.626 51.543 6 50.983 6z"/><path id="Shape" fill="#E8C48F" d="M84.193 9.36h-26.39V6.085C57.803 2.729 54.99 0 51.528 0H36.47c-3.46 0-6.275 2.729-6.275 6.085V9.36H3.807C1.705 9.36 0 11.012 0 13.05v.26C0 15.348 1.705 17 3.807 17h80.386C86.295 17 88 15.348 88 13.31v-.26c0-2.038-1.706-3.69-3.807-3.69zM53 12H36V7.395C36 6.626 36.457 6 37.016 6h14.968C52.544 6 53 6.626 53 7.395V12zM74.955 20.045H8.044c-3.89 0-7.044-.68-7.044 3.266l5.282 78.382c0 3.943 3.155 7.307 7.045 7.307h56.347c3.89 0 7.044-3.364 7.044-7.307L82 23.31c-.001-3.947-3.155-3.266-7.045-3.266zM26.757 98.999c-1.283.039-2.353-.8-2.396-1.878l-2.36-61.095c-.041-1.078.964-1.985 2.242-2.025 1.283-.04 2.353.801 2.396 1.879l2.36 61.096c.041 1.076-.963 1.984-2.242 2.023zM43 97.049C43 98.126 42.328 99 41.5 99s-1.5-.876-1.5-1.951V35.95c0-1.078.672-1.951 1.5-1.951s1.5.873 1.5 1.951V97.05zm18.639.072c-.042 1.078-1.113 1.917-2.396 1.878-1.28-.04-2.283-.947-2.242-2.024l2.36-61.095c.042-1.078 1.112-1.919 2.394-1.879 1.28.042 2.285.947 2.244 2.025l-2.36 61.095z"/></g></g></g></svg>
|
After Width: | Height: | Size: 3.6 KiB |
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 8.3 KiB |
1
1-js/02-first-steps/04-variables/variable.svg
Normal file
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="166" height="145" viewBox="0 0 166 145"><defs><style>@import url(https://fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic%7CPT+Mono);@font-face{font-family:'PT Mono';font-weight:700;font-style:normal;src:local('PT MonoBold'),url(/font/PTMonoBold.woff2) format('woff2'),url(/font/PTMonoBold.woff) format('woff'),url(/font/PTMonoBold.ttf) format('truetype')}</style></defs><g id="combined" fill="none" fill-rule="evenodd" stroke="none" stroke-width="1"><g id="variable.svg"><g id="noun_1211_cc-+-Message" transform="translate(13 3)"><g id="noun_1211_cc"><path id="Shape" fill="#E8C48F" d="M17 37.196h112.558v42.95c0 .373-.079.862-.279 1.294-.2.433-16.574 35.56-16.574 35.56V62.64l16.854-25.444L148 9H35.44L17 37.196zM17 66V38L2 66"/><g id="Rectangle-5-+-"World!"" transform="translate(15)"><path id="Rectangle-5" fill="#FFF9EB" stroke="#8A704D" stroke-width="2" d="M18.861 1.809L2 17.533l53.14 56.986L72 58.794 18.861 1.81z"/><text id=""Hello!"" fill="#8A704D" font-family="OpenSans-Bold, Open Sans" font-size="14" font-weight="bold" transform="rotate(47 40.083 39.762)"><tspan x="10.591" y="46.262">"Hello!"</tspan></text></g><path id="Shape" fill="#E8C48F" d="M0 68v54.73c0 3.42 1.484 5.27 4.387 5.27h100.086c3.122 0 5.527-2.548 5.527-3.476V68H0z"/></g><text id="message" fill="#FFF" font-family="OpenSans-Bold, Open Sans" font-size="18" font-weight="bold"><tspan x="17" y="105">message</tspan></text></g></g></g></svg>
|
After Width: | Height: | Size: 1.5 KiB |
Before Width: | Height: | Size: 19 KiB |
|
@ -1,6 +1,6 @@
|
|||
# Data types
|
||||
|
||||
A variable in JavaScript can contain any data. A variable can at one moment be a string and later receive a numeric value:
|
||||
A variable in JavaScript can contain any data. A variable can at one moment be a string and at another be a number:
|
||||
|
||||
```js
|
||||
// no error
|
||||
|
@ -10,20 +10,20 @@ message = 123456;
|
|||
|
||||
Programming languages that allow such things are called "dynamically typed", meaning that there are data types, but variables are not bound to any of them.
|
||||
|
||||
There are seven basic data types in JavaScript. Here we'll study the basics, and in the next chapters we'll talk about each of them in detail.
|
||||
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.
|
||||
|
||||
## A number
|
||||
## Number
|
||||
|
||||
```js
|
||||
let n = 123;
|
||||
n = 12.345;
|
||||
```
|
||||
|
||||
The *number* type serves both for integer and floating point numbers.
|
||||
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.
|
||||
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 that type: `Infinity`, `-Infinity` and `NaN`.
|
||||
Besides regular numbers, there are so-called "special numeric values" which also belong to this data type: `Infinity`, `-Infinity` and `NaN`.
|
||||
|
||||
- `Infinity` represents the mathematical [Infinity](https://en.wikipedia.org/wiki/Infinity) ∞. It is a special value that's greater than any number.
|
||||
|
||||
|
@ -33,7 +33,7 @@ Besides regular numbers, there are so-called "special numeric values" which also
|
|||
alert( 1 / 0 ); // Infinity
|
||||
```
|
||||
|
||||
Or just mention it in the code directly:
|
||||
Or just reference it directly:
|
||||
|
||||
```js run
|
||||
alert( Infinity ); // Infinity
|
||||
|
@ -44,32 +44,51 @@ Besides regular numbers, there are so-called "special numeric values" which also
|
|||
alert( "not a number" / 2 ); // NaN, such division is erroneous
|
||||
```
|
||||
|
||||
`NaN` is sticky. Any further operation on `NaN` would give `NaN`:
|
||||
`NaN` is sticky. Any further operation on `NaN` returns `NaN`:
|
||||
|
||||
```js run
|
||||
alert( "not a number" / 2 + 5 ); // NaN
|
||||
```
|
||||
|
||||
So, if there's `NaN` somewhere in a mathematical expression, it propagates to the whole result.
|
||||
So, if there's a `NaN` somewhere in a mathematical expression, it propagates to the whole result.
|
||||
|
||||
```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.
|
||||
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.
|
||||
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 a common sense of this word.
|
||||
Special numeric values formally belong to the "number" type. Of course they are not numbers in the common sense of this word.
|
||||
|
||||
We'll see more about working with numbers in the chapter <info:number>.
|
||||
|
||||
## A string
|
||||
## BigInt
|
||||
|
||||
A string in JavaScript must be quoted.
|
||||
In JavaScript, the "number" type cannot represent integer values larger than <code>2<sup>53</sup></code> (or less than <code>-2<sup>53</sup></code> for negatives), that's a technical limitation caused by their internal representation. That's about 16 decimal digits, so for most purposes the limitation isn't a problem, but sometimes we need really big numbers, e.g. for cryptography or microsecond-precision timestamps.
|
||||
|
||||
`BigInt` type was recently added to the language to represent integers of arbitrary length.
|
||||
|
||||
A `BigInt` is created by appending `n` to the end of an integer literal:
|
||||
|
||||
```js
|
||||
// the "n" at the end means it's a BigInt
|
||||
const bigInt = 1234567890123456789012345678901234567890n;
|
||||
```
|
||||
|
||||
As `BigInt` numbers are rarely needed, we devoted them a separate chapter <info:bigint>.
|
||||
|
||||
```smart header="Compatability issues"
|
||||
Right now `BigInt` is supported in Firefox and Chrome, but not in Safari/IE/Edge.
|
||||
```
|
||||
|
||||
## String
|
||||
|
||||
A string in JavaScript must be surrounded by quotes.
|
||||
|
||||
```js
|
||||
let str = "Hello";
|
||||
let str2 = 'Single quotes are ok too';
|
||||
let phrase = `can embed ${str}`;
|
||||
let phrase = `can embed another ${str}`;
|
||||
```
|
||||
|
||||
In JavaScript, there are 3 types of quotes.
|
||||
|
@ -78,7 +97,7 @@ In JavaScript, there are 3 types of quotes.
|
|||
2. Single quotes: `'Hello'`.
|
||||
3. Backticks: <code>`Hello`</code>.
|
||||
|
||||
Double and single quotes are "simple" quotes. There's no difference between them in JavaScript.
|
||||
Double and single quotes are "simple" quotes. There's practically no difference between them in JavaScript.
|
||||
|
||||
Backticks are "extended functionality" quotes. They allow us to embed variables and expressions into a string by wrapping them in `${…}`, for example:
|
||||
|
||||
|
@ -92,9 +111,9 @@ alert( `Hello, *!*${name}*/!*!` ); // Hello, John!
|
|||
alert( `the result is *!*${1 + 2}*/!*` ); // the result is 3
|
||||
```
|
||||
|
||||
The expression inside `${…}` is evaluated and the result becomes a part of the string. We can put anything there: a variable like `name` or an arithmetical expression like `1 + 2` or something more complex.
|
||||
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 do not allow such embedding!
|
||||
Please note that this can only be done in backticks. Other quotes don't have this embedding functionality!
|
||||
```js run
|
||||
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
|
||||
```
|
||||
|
@ -102,12 +121,12 @@ alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do n
|
|||
We'll cover strings more thoroughly in the chapter <info:string>.
|
||||
|
||||
```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 `char`.
|
||||
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 only one character or many of them.
|
||||
```
|
||||
|
||||
## A boolean (logical type)
|
||||
## Boolean (logical type)
|
||||
|
||||
The boolean type has only two values: `true` and `false`.
|
||||
|
||||
|
@ -128,31 +147,31 @@ let isGreater = 4 > 1;
|
|||
alert( isGreater ); // true (the comparison result is "yes")
|
||||
```
|
||||
|
||||
We'll cover booleans more deeply later in the chapter <info:logical-operators>.
|
||||
We'll cover booleans more deeply in the chapter <info:logical-operators>.
|
||||
|
||||
## The "null" value
|
||||
|
||||
The special `null` value does not belong to any type of those described above.
|
||||
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:
|
||||
It forms a separate type of its own which contains only the `null` value:
|
||||
|
||||
```js
|
||||
let age = null;
|
||||
```
|
||||
|
||||
In JavaScript `null` is not a "reference to a non-existing object" or a "null pointer" like in some other languages.
|
||||
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 has the sense of "nothing", "empty" or "value unknown".
|
||||
It's just a special value which represents "nothing", "empty" or "value unknown".
|
||||
|
||||
The code above states that the `age` is unknown or empty for some reason.
|
||||
The code above states that `age` is unknown or empty for some reason.
|
||||
|
||||
## The "undefined" value
|
||||
|
||||
The special value `undefined` stands apart. It makes a type of its own, just like `null`.
|
||||
The special value `undefined` also stands apart. It makes a type of its own, just like `null`.
|
||||
|
||||
The meaning of `undefined` is "value is not assigned".
|
||||
|
||||
If a variable is declared, but not assigned, then its value is exactly `undefined`:
|
||||
If a variable is declared, but not assigned, then its value is `undefined`:
|
||||
|
||||
```js run
|
||||
let x;
|
||||
|
@ -170,26 +189,26 @@ x = undefined;
|
|||
alert(x); // "undefined"
|
||||
```
|
||||
|
||||
...But it's not recommended to do that. Normally, we use `null` to write an "empty" or an "unknown" value into the variable, and `undefined` is only used for checks, to see if the variable is assigned or similar.
|
||||
...But we don't recommend doing that. Normally, we use `null` to assign an "empty" or "unknown" value to a variable, and we use `undefined` for checks like seeing if a variable has been assigned.
|
||||
|
||||
## Objects and Symbols
|
||||
|
||||
The `object` type is special.
|
||||
|
||||
All other types are called "primitive", because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We'll deal with them later in the chapter <info:object> after we know enough about primitives.
|
||||
All other types are called "primitive" because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities. We'll deal with them later in the chapter <info:object> after we learn more about primitives.
|
||||
|
||||
The `symbol` type is used to create unique identifiers for objects. We have to mention it here for completeness, but it's better to study them after objects.
|
||||
The `symbol` type is used to create unique identifiers for objects. We mention it here for completeness, but we'll study it after objects.
|
||||
|
||||
## The typeof operator [#type-typeof]
|
||||
|
||||
The `typeof` operator returns the type of the argument. It's useful when we want to process values of different types differently, or just want to make a quick check.
|
||||
The `typeof` operator returns the type of the argument. It's useful when we want to process values of different types differently or just want to do a quick check.
|
||||
|
||||
It supports two forms of syntax:
|
||||
|
||||
1. As an operator: `typeof x`.
|
||||
2. Function style: `typeof(x)`.
|
||||
2. As a function: `typeof(x)`.
|
||||
|
||||
In other words, it works both with parentheses or without them. The result is the same.
|
||||
In other words, it works with parentheses or without them. The result is the same.
|
||||
|
||||
The call to `typeof x` returns a string with the type name:
|
||||
|
||||
|
@ -198,6 +217,8 @@ typeof undefined // "undefined"
|
|||
|
||||
typeof 0 // "number"
|
||||
|
||||
typeof 10n // "bigint"
|
||||
|
||||
typeof true // "boolean"
|
||||
|
||||
typeof "foo" // "string"
|
||||
|
@ -217,18 +238,18 @@ typeof alert // "function" (3)
|
|||
*/!*
|
||||
```
|
||||
|
||||
The last three lines may need additional explanations:
|
||||
|
||||
1. `Math` is a built-in object that provides mathematical operations. We will learn it in the chapter <info:number>. Here it serves just as an example of an object.
|
||||
2. The result of `typeof null` is `"object"`. That's wrong. It is an officially recognized error in `typeof`, kept for compatibility. Of course, `null` is not an object. It is a special value with a separate type of its own. So, again, that's an error in the language.
|
||||
3. The result of `typeof alert` is `"function"`, because `alert` is a function of the language. We'll study functions in the next chapters, and we'll see that there's no special "function" type in the language. Functions belong to the object type. But `typeof` treats them differently. Formally, it's incorrect, but very convenient in practice.
|
||||
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 <info:number>. Here, it serves just as an example of an object.
|
||||
2. The result of `typeof null` is `"object"`. That's wrong. It is an officially recognized error in `typeof`, kept for compatibility. Of course, `null` is not an object. It is a special value with a separate type of its own. So, again, this is an error in the language.
|
||||
3. The result of `typeof alert` is `"function"`, because `alert` is a function. We'll study functions in the next chapters where we'll also see that there's no special "function" type in JavaScript. Functions belong to the object type. But `typeof` treats them differently, returning `"function"`. That's not quite correct, but very convenient in practice.
|
||||
|
||||
## Summary
|
||||
|
||||
There are 7 basic types in JavaScript.
|
||||
There are 8 basic data types in JavaScript.
|
||||
|
||||
- `number` for numbers of any kind: integer or floating-point.
|
||||
- `number` for numbers of any kind: integer or floating-point, integers are limited by ±2<sup>53</sup>.
|
||||
- `bigint` is for integer numbers of arbitrary length.
|
||||
- `string` for strings. A string may have one 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`.
|
||||
|
@ -236,10 +257,10 @@ There are 7 basic types in JavaScript.
|
|||
- `object` for more complex data structures.
|
||||
- `symbol` for unique identifiers.
|
||||
|
||||
The `typeof` operator allows us to see which type is stored in the variable.
|
||||
The `typeof` operator allows us to see which type is stored in a variable.
|
||||
|
||||
- Two forms: `typeof x` or `typeof(x)`.
|
||||
- Returns a string with the name of the type, like `"string"`.
|
||||
- For `null` returns `"object"` -- that's an error in the language, it's not an object in fact.
|
||||
- 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, then we'll move on to objects.
|
||||
In the next chapters, we'll concentrate on primitive values and once we're familiar with them, we'll move on to objects.
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
|
||||
```js no-beautify
|
||||
"" + 1 + 0 = "10" // (1)
|
||||
"" - 1 + 0 = -1 // (2)
|
||||
true + false = 1
|
||||
6 / "3" = 2
|
||||
"2" * "3" = 6
|
||||
4 + 5 + "px" = "9px"
|
||||
"$" + 4 + 5 = "$45"
|
||||
"4" - 2 = 2
|
||||
"4px" - 2 = NaN
|
||||
7 / 0 = Infinity
|
||||
" -9\n" + 5 = " -9\n5"
|
||||
" -9\n" - 5 = -14
|
||||
null + 1 = 1 // (3)
|
||||
undefined + 1 = NaN // (4)
|
||||
```
|
||||
|
||||
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. `null` becomes `0` after the numeric conversion.
|
||||
4. `undefined` becomes `NaN` after the numeric conversion.
|
|
@ -1,22 +1,22 @@
|
|||
# Type Conversions
|
||||
|
||||
Most of the time, operators and functions automatically convert a value to the right type. That's called "type conversion".
|
||||
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 put things right.
|
||||
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 don't cover objects yet. Here we study primitives first. Later, after we learn objects, we'll see how object conversion works in the chapter <info:object-toprimitive>.
|
||||
In this chapter, we won't cover objects. Instead, we'll study primitives first. Later, after we learn about objects, we'll see how object conversion works in the chapter <info:object-toprimitive>.
|
||||
```
|
||||
|
||||
## ToString
|
||||
## 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 use a call `String(value)` function for that:
|
||||
We can also call the `String(value)` function to convert a value to a string:
|
||||
|
||||
```js run
|
||||
let value = true;
|
||||
|
@ -28,9 +28,9 @@ alert(typeof value); // string
|
|||
*/!*
|
||||
```
|
||||
|
||||
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"` etc.
|
||||
String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc.
|
||||
|
||||
## ToNumber
|
||||
## Numeric Conversion
|
||||
|
||||
Numeric conversion happens in mathematical functions and expressions automatically.
|
||||
|
||||
|
@ -40,7 +40,7 @@ For example, when division `/` is applied to non-numbers:
|
|||
alert( "6" / "2" ); // 3, strings are converted to numbers
|
||||
```
|
||||
|
||||
We can use a `Number(value)` function to explicitly convert a `value`:
|
||||
We can use the `Number(value)` function to explicitly convert a `value` to a number:
|
||||
|
||||
```js run
|
||||
let str = "123";
|
||||
|
@ -51,9 +51,9 @@ let num = Number(str); // becomes a number 123
|
|||
alert(typeof num); // number
|
||||
```
|
||||
|
||||
Explicit conversion is usually required when we read a value from a string-based source like a text form, but we expect a number to be entered.
|
||||
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 conversion is `NaN`, for instance:
|
||||
If the string is not a valid number, the result of such a conversion is `NaN`. For instance:
|
||||
|
||||
```js run
|
||||
let age = Number("an arbitrary string instead of a number");
|
||||
|
@ -68,7 +68,7 @@ Numeric conversion rules:
|
|||
|`undefined`|`NaN`|
|
||||
|`null`|`0`|
|
||||
|<code>true and false</code> | `1` and `0` |
|
||||
| `string` | Whitespaces from the start and the end are removed. Then, if the remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. |
|
||||
| `string` | Whitespaces 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:
|
||||
|
||||
|
@ -79,30 +79,19 @@ alert( Number(true) ); // 1
|
|||
alert( Number(false) ); // 0
|
||||
```
|
||||
|
||||
Please note that `null` and `undefined` behave differently here: `null` becomes a zero, while `undefined` becomes `NaN`.
|
||||
Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`.
|
||||
|
||||
````smart header="Addition '+' concatenates strings"
|
||||
Almost all mathematical operations convert values to numbers. With a notable exception of the addition `+`. If one of the added values is a string, then another one is also converted to a string.
|
||||
Most mathematical operators also perform such conversion, we'll see that in the next chapter.
|
||||
|
||||
Then it concatenates (joins) them:
|
||||
|
||||
```js run
|
||||
alert( 1 + '2' ); // '12' (string to the right)
|
||||
alert( '1' + 2 ); // '12' (string to the left)
|
||||
```
|
||||
|
||||
That only happens when one of the arguments is a string. Otherwise, values are converted to numbers.
|
||||
````
|
||||
|
||||
## ToBoolean
|
||||
## Boolean Conversion
|
||||
|
||||
Boolean conversion is the simplest one.
|
||||
|
||||
It happens in logical operations (later we'll meet condition tests and other kinds of them), but also can be performed manually with the call of `Boolean(value)`.
|
||||
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`.
|
||||
- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`.
|
||||
- Other values become `true`.
|
||||
|
||||
For instance:
|
||||
|
@ -116,7 +105,7 @@ alert( Boolean("") ); // false
|
|||
```
|
||||
|
||||
````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`.
|
||||
Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`.
|
||||
|
||||
```js run
|
||||
alert( Boolean("0") ); // true
|
||||
|
@ -124,14 +113,13 @@ alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
|
|||
```
|
||||
````
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
There are three most widely used type conversions: to string, to number and to boolean.
|
||||
The three most widely used type conversions are to string, to number, and to boolean.
|
||||
|
||||
**`ToString`** -- Occurs when we output something, can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
|
||||
**`String Conversion`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values.
|
||||
|
||||
**`ToNumber`** -- Occurs in math operations, can be performed with `Number(value)`.
|
||||
**`Numeric Conversion`** -- Occurs in math operations. Can be performed with `Number(value)`.
|
||||
|
||||
The conversion follows the rules:
|
||||
|
||||
|
@ -142,7 +130,7 @@ The conversion follows the rules:
|
|||
|<code>true / false</code> | `1 / 0` |
|
||||
| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. |
|
||||
|
||||
**`ToBoolean`** -- Occurs in logical operations, or can be performed with `Boolean(value)`.
|
||||
**`Boolean Conversion`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
|
||||
|
||||
Follows the rules:
|
||||
|
||||
|
@ -157,4 +145,4 @@ Most of these rules are easy to understand and memorize. The notable exceptions
|
|||
- `undefined` is `NaN` as a number, not `0`.
|
||||
- `"0"` and space-only strings like `" "` are true as a boolean.
|
||||
|
||||
Objects are not covered here, we'll return to them later in the chapter <info:object-toprimitive> that is devoted exclusively to objects, after we learn more basic things about JavaScript.
|
||||
Objects aren't covered here. We'll return to them later in the chapter <info:object-toprimitive> that is devoted exclusively to objects after we learn more basic things about JavaScript.
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
|
||||
```js no-beautify
|
||||
"" + 1 + 0 = "10" // (1)
|
||||
"" - 1 + 0 = -1 // (2)
|
||||
true + false = 1
|
||||
6 / "3" = 2
|
||||
"2" * "3" = 6
|
||||
4 + 5 + "px" = "9px"
|
||||
"$" + 4 + 5 = "$45"
|
||||
"4" - 2 = 2
|
||||
"4px" - 2 = NaN
|
||||
7 / 0 = Infinity
|
||||
" -9 " + 5 = " -9 5" // (3)
|
||||
" -9 " - 5 = -14 // (4)
|
||||
null + 1 = 1 // (5)
|
||||
undefined + 1 = NaN // (6)
|
||||
" \t \n" - 2 = -2 // (7)
|
||||
```
|
||||
|
||||
1. The addition with a string `"" + 1` converts `1` to a string: `"" + 1 = "1"`, and then we have `"1" + 0`, the same rule is applied.
|
||||
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`.
|
|
@ -17,10 +17,11 @@ true + false
|
|||
"4" - 2
|
||||
"4px" - 2
|
||||
7 / 0
|
||||
" -9\n" + 5
|
||||
" -9\n" - 5
|
||||
" -9 " + 5
|
||||
" -9 " - 5
|
||||
null + 1
|
||||
undefined + 1
|
||||
" \t \n" - 2
|
||||
```
|
||||
|
||||
Think well, write down and then compare with the answer.
|
|
@ -1,15 +1,15 @@
|
|||
# Operators
|
||||
|
||||
Many operators are known to us from school. They are addition `+`, a multiplication `*`, a subtraction `-` and so on.
|
||||
We know many operators from school. They are things like addition `+`, multiplication `*`, subtraction `-`, and so on.
|
||||
|
||||
In this chapter we concentrate on aspects that are not covered by school arithmetic.
|
||||
In this chapter, we'll concentrate on aspects of operators that are not covered by school arithmetic.
|
||||
|
||||
## Terms: "unary", "binary", "operand"
|
||||
|
||||
Before we move on, let's grasp the common terminology.
|
||||
Before we move on, let's grasp some common terminology.
|
||||
|
||||
- *An operand* -- is what operators are applied to. For instance in multiplication `5 * 2` there are two operands: the left operand is `5`, and the right operand is `2`. Sometimes people say "arguments" instead of "operands".
|
||||
- An operator is *unary* if it has a single operand. For example, the unary negation `-` reverses the sign of the number:
|
||||
- *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:
|
||||
|
||||
```js run
|
||||
let x = 1;
|
||||
|
@ -19,29 +19,29 @@ Before we move on, let's grasp the common terminology.
|
|||
*/!*
|
||||
alert( x ); // -1, unary negation was applied
|
||||
```
|
||||
- An operator is *binary* if it has two operands. The same minus exists in the binary form as well:
|
||||
- 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, we're talking about two different operators here: the unary negation (single operand, reverses the sign) and the binary subtraction (two operands, subtracts).
|
||||
Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction operator, a binary operator that subtracts one number from another.
|
||||
|
||||
## Strings concatenation, binary +
|
||||
## String concatenation, binary +
|
||||
|
||||
Now let's see special features of JavaScript operators that are beyond school arithmetics.
|
||||
Now, let's see special features of JavaScript operators that are beyond school arithmetics.
|
||||
|
||||
Usually the plus operator `+` sums numbers.
|
||||
Usually, the plus operator `+` sums numbers.
|
||||
|
||||
But if the binary `+` is applied to strings, it merges (concatenates) them:
|
||||
But, if the binary `+` is applied to strings, it merges (concatenates) them:
|
||||
|
||||
```js
|
||||
let s = "my" + "string";
|
||||
alert(s); // mystring
|
||||
```
|
||||
|
||||
Note that if any of the operands is a string, then the other one is converted to a string too.
|
||||
Note that if one of the operands is a string, the other one is converted to a string too.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -50,7 +50,7 @@ alert( '1' + 2 ); // "12"
|
|||
alert( 2 + '1' ); // "21"
|
||||
```
|
||||
|
||||
See, it doesn't matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, then convert the other one into a string as well.
|
||||
See, it doesn't matter whether the first operand is a string or the second one. The rule is simple: if either operand is a string, the other one is converted into a string as well.
|
||||
|
||||
However, note that operations run from left to right. If there are two numbers followed by a string, the numbers will be added before being converted to a string:
|
||||
|
||||
|
@ -59,7 +59,7 @@ However, note that operations run from left to right. If there are two numbers f
|
|||
alert(2 + 2 + '1' ); // "41" and not "221"
|
||||
```
|
||||
|
||||
String concatenation and conversion is a special feature of the binary plus `+`. Other arithmetic operators work only with numbers. They always convert their operands to numbers.
|
||||
String concatenation and conversion is a special feature of the binary plus `+`. Other arithmetic operators work only with numbers and always convert their operands to numbers.
|
||||
|
||||
For instance, subtraction and division:
|
||||
|
||||
|
@ -70,9 +70,9 @@ alert( '6' / '2' ); // 3
|
|||
|
||||
## Numeric conversion, unary +
|
||||
|
||||
The plus `+` exists in two forms. The binary form that we used above and the unary form.
|
||||
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 with numbers, but if the operand is not a number, then it is converted into it.
|
||||
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:
|
||||
|
||||
|
@ -91,11 +91,9 @@ alert( +"" ); // 0
|
|||
*/!*
|
||||
```
|
||||
|
||||
It actually does the same as `Number(...)`, but is shorter.
|
||||
It actually does the same thing as `Number(...)`, but is shorter.
|
||||
|
||||
A need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, then they are usually strings.
|
||||
|
||||
What if we want to sum them?
|
||||
The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?
|
||||
|
||||
The binary plus would add them as strings:
|
||||
|
||||
|
@ -106,7 +104,7 @@ let oranges = "3";
|
|||
alert( apples + oranges ); // "23", the binary plus concatenates strings
|
||||
```
|
||||
|
||||
If we want to treat them as numbers, then we can convert and then sum:
|
||||
If we want to treat them as numbers, we need to convert and then sum them:
|
||||
|
||||
```js run
|
||||
let apples = "2";
|
||||
|
@ -121,21 +119,21 @@ alert( +apples + +oranges ); // 5
|
|||
// 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.
|
||||
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 one? As we're going to see, that's because of their *higher precedence*.
|
||||
Why are unary pluses applied to values before the binary ones? As we're going to see, that's because of their *higher precedence*.
|
||||
|
||||
## Operators precedence
|
||||
## Operator precedence
|
||||
|
||||
If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, there's an implicit priority order among the operators.
|
||||
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.
|
||||
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 order, we can use them, like: `(1 + 2) * 2`.
|
||||
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 bigger number executes first. If the precedence is the same, the execution order is from left to right.
|
||||
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.
|
||||
|
||||
An extract from the [precedence table](https://developer.mozilla.org/en/JavaScript/Reference/operators/operator_precedence) (you don't need to remember this, but note that unary operators are higher than corresponding binary ones):
|
||||
Here's an extract from the [precedence table](https://developer.mozilla.org/en/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 |
|
||||
|------------|------|------|
|
||||
|
@ -150,13 +148,13 @@ An extract from the [precedence table](https://developer.mozilla.org/en/JavaScri
|
|||
| 3 | assignment | `=` |
|
||||
| ... | ... | ... |
|
||||
|
||||
As we can see, the "unary plus" has a priority of `16`, which is higher than `13` for the "addition" (binary plus). That's why in the expression `"+apples + +oranges"` unary pluses work first, and then the addition.
|
||||
As we can see, the "unary plus" has a priority of `16` which is higher than the `13` 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 `3`.
|
||||
|
||||
That's why when we assign a variable, like `x = 2 * 2 + 1`, then the calculations are done first, and afterwards the `=` is evaluated, storing the result in `x`.
|
||||
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`.
|
||||
|
||||
```js
|
||||
let x = 2 * 2 + 1;
|
||||
|
@ -178,14 +176,14 @@ alert( b ); // 4
|
|||
alert( c ); // 4
|
||||
```
|
||||
|
||||
Chained assignments evaluate from right to left. First the rightmost expression `2 + 2` is evaluated then assigned to the variables on the left: `c`, `b` and `a`. At the end, all variables share a single value.
|
||||
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.
|
||||
|
||||
````smart header="The assignment operator `\"=\"` returns a value"
|
||||
An operator always returns a value. That's obvious for most of them like an addition `+` or a multiplication `*`. But the assignment operator follows that rule too.
|
||||
An operator always returns a value. That's obvious for most of them like addition `+` or multiplication `*`. But the assignment operator follows this rule too.
|
||||
|
||||
The call `x = value` writes the `value` into `x` *and then returns it*.
|
||||
|
||||
Here's the demo that uses an assignment as part of a more complex expression:
|
||||
Here's a demo that uses an assignment as part of a more complex expression:
|
||||
|
||||
```js run
|
||||
let a = 1;
|
||||
|
@ -199,14 +197,14 @@ alert( a ); // 3
|
|||
alert( c ); // 0
|
||||
```
|
||||
|
||||
In the example above, the result of `(a = b + 1)` is the value which is assigned to `a` (that is `3`). It is then used to subtract from `3`.
|
||||
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 can see it in 3rd-party libraries, but shouldn't write anything like that ourselves. Such tricks definitely don't make the code clearer and readable.
|
||||
Funny code, isn't it? We should understand how it works, because sometimes we see it in JavaScript libraries, but shouldn't write anything like that ourselves. Such tricks definitely don't make code clearer or readable.
|
||||
````
|
||||
|
||||
## Remainder %
|
||||
|
||||
The remainder operator `%` despite its look does not have a relation to percents.
|
||||
The remainder operator `%`, despite its appearance, is not related to percents.
|
||||
|
||||
The result of `a % b` is the remainder of the integer division of `a` by `b`.
|
||||
|
||||
|
@ -232,7 +230,9 @@ alert( 2 ** 3 ); // 8 (2 * 2 * 2)
|
|||
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)
|
||||
```
|
||||
|
||||
The operator works for non-integer numbers of `a` and `b` as well, for instance:
|
||||
The operator works for non-integer numbers as well.
|
||||
|
||||
For instance:
|
||||
|
||||
```js run
|
||||
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths)
|
||||
|
@ -245,39 +245,39 @@ alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
|
|||
|
||||
Increasing or decreasing a number by one is among the most common numerical operations.
|
||||
|
||||
So, there are special operators for that:
|
||||
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
|
||||
counter++; // works the same as counter = counter + 1, but is shorter
|
||||
alert( counter ); // 3
|
||||
```
|
||||
- **Decrement** `--` decreases a variable by 1:
|
||||
|
||||
```js run no-beautify
|
||||
let counter = 2;
|
||||
counter--; // works the same as counter = counter - 1, but is shorter
|
||||
counter--; // works the same as counter = counter - 1, but is shorter
|
||||
alert( counter ); // 1
|
||||
```
|
||||
|
||||
```warn
|
||||
Increment/decrement can be applied only to a variable. An attempt to use it on a value like `5++` will give an error.
|
||||
Increment/decrement can only be applied to variables. Trying to use it on a value like `5++` will give an error.
|
||||
```
|
||||
|
||||
Operators `++` and `--` can be placed both after and before the variable.
|
||||
The operators `++` and `--` can be placed either before or after a variable.
|
||||
|
||||
- When the operator goes after the variable, it is called a "postfix form": `counter++`.
|
||||
- The "prefix form" is when the operator stands before the variable: `++counter`.
|
||||
- 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 records do the same: increase `counter` by `1`.
|
||||
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 not an exception here. The prefix form returns the new value, while the postfix form returns the old value (prior to increment/decrement).
|
||||
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 the example:
|
||||
To see the difference, here's an example:
|
||||
|
||||
```js run
|
||||
let counter = 1;
|
||||
|
@ -286,9 +286,9 @@ let a = ++counter; // (*)
|
|||
alert(a); // *!*2*/!*
|
||||
```
|
||||
|
||||
Here in the line `(*)` the prefix call `++counter` increments `counter` and returns the new value that is `2`. So the `alert` shows `2`.
|
||||
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:
|
||||
Now, let's use the postfix form:
|
||||
|
||||
```js run
|
||||
let counter = 1;
|
||||
|
@ -297,11 +297,11 @@ let a = counter++; // (*) changed ++counter to counter++
|
|||
alert(a); // *!*1*/!*
|
||||
```
|
||||
|
||||
In the line `(*)` the *postfix* form `counter++` also increments `counter`, but returns the *old* value (prior to increment). So the `alert` shows `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, then there is no difference in which form to use:
|
||||
- If the result of increment/decrement is not used, there is no difference in which form to use:
|
||||
|
||||
```js run
|
||||
let counter = 0;
|
||||
|
@ -309,13 +309,13 @@ To summarize:
|
|||
++counter;
|
||||
alert( counter ); // 2, the lines above did the same
|
||||
```
|
||||
- If we'd like to increase the value *and* use the result of the operator right now, then we need the prefix form:
|
||||
- If we'd like to increase a value *and* immediately use the result of the operator, we need the prefix form:
|
||||
|
||||
```js run
|
||||
let counter = 0;
|
||||
alert( ++counter ); // 1
|
||||
```
|
||||
- If we'd like to increment, but use the previous value, then we need the postfix form:
|
||||
- If we'd like to increment a value but use its previous value, we need the postfix form:
|
||||
|
||||
```js run
|
||||
let counter = 0;
|
||||
|
@ -323,7 +323,7 @@ To summarize:
|
|||
```
|
||||
|
||||
````smart header="Increment/decrement among other operators"
|
||||
Operators `++/--` can be used inside an expression as well. Their precedence is higher than most other arithmetical operations.
|
||||
The operators `++/--` can be used inside expressions as well. Their precedence is higher than most other arithmetical operations.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -339,11 +339,11 @@ let counter = 1;
|
|||
alert( 2 * counter++ ); // 2, because counter++ returns the "old" value
|
||||
```
|
||||
|
||||
Though technically allowable, such notation usually makes the code less readable. One line does multiple things -- not good.
|
||||
Though technically okay, such notation usually makes code less readable. One line does multiple things -- not good.
|
||||
|
||||
While reading the code, a fast "vertical" eye-scan can easily miss such `counter++`, and it won't be obvious that the variable increases.
|
||||
While reading code, a fast "vertical" eye-scan can easily miss something like `counter++` and it won't be obvious that the variable increased.
|
||||
|
||||
The "one line -- one action" style is advised:
|
||||
We advise a style of "one line -- one action":
|
||||
|
||||
```js run
|
||||
let counter = 1;
|
||||
|
@ -368,11 +368,11 @@ The list of operators:
|
|||
- RIGHT SHIFT ( `>>` )
|
||||
- ZERO-FILL RIGHT SHIFT ( `>>>` )
|
||||
|
||||
These operators are used very rarely. To understand them, we should delve into low-level number representation, and it would not be optimal to do that right now. Especially because we won't need them any time soon. If you're curious, you can read the [Bitwise Operators](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) article in MDN. It would be more practical to do that when a real need arises.
|
||||
These operators are used very rarely. To understand them, we need to delve into low-level number representation and it would not be optimal to do that right now, especially since we won't need them any time soon. If you're curious, you can read the [Bitwise Operators](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) article on MDN. It would be more practical to do that when a real need arises.
|
||||
|
||||
## Modify-in-place
|
||||
|
||||
We often need to apply an operator to a variable and store the new result in it.
|
||||
We often need to apply an operator to a variable and store the new result in that same variable.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -382,7 +382,7 @@ n = n + 5;
|
|||
n = n * 2;
|
||||
```
|
||||
|
||||
This notation can be shortened using operators `+=` and `*=`:
|
||||
This notation can be shortened using the operators `+=` and `*=`:
|
||||
|
||||
```js run
|
||||
let n = 2;
|
||||
|
@ -392,7 +392,7 @@ n *= 2; // now n = 14 (same as n = n * 2)
|
|||
alert( n ); // 14
|
||||
```
|
||||
|
||||
Short "modify-and-assign" operators exist for all arithmetical and bitwise operators: `/=`, `-=` etc.
|
||||
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:
|
||||
|
||||
|
@ -406,9 +406,9 @@ alert( n ); // 16 (right part evaluated first, same as n *= 8)
|
|||
|
||||
## Comma
|
||||
|
||||
The comma operator `,` is one of most rare and 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 `,` 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 the result of only the last one is returned.
|
||||
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:
|
||||
|
||||
|
@ -420,17 +420,17 @@ let a = (1 + 2, 3 + 4);
|
|||
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.
|
||||
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 then the number after the comma `7` is not processed anyhow, so it's ignored.
|
||||
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 such an operator which throws away everything except the last part?
|
||||
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.
|
||||
Sometimes, people use it in more complex constructs to put several actions in one line.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -441,4 +441,4 @@ for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) {
|
|||
}
|
||||
```
|
||||
|
||||
Such tricks are used in many JavaScript frameworks, that's why we mention them. But usually they don't improve the code readability, so we should think well before writing like that.
|
||||
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.
|
||||
|
|
|
@ -3,19 +3,19 @@
|
|||
```js no-beautify
|
||||
5 > 4 → true
|
||||
"apple" > "pineapple" → false
|
||||
"2" > "12" → true
|
||||
undefined == null → true
|
||||
undefined === null → false
|
||||
"2" > "12" → true
|
||||
undefined == null → true
|
||||
undefined === null → false
|
||||
null == "\n0\n" → false
|
||||
null === +"\n0\n" → false
|
||||
null === +"\n0\n" → false
|
||||
```
|
||||
|
||||
Some of the reasons:
|
||||
|
||||
1. Obviously, true.
|
||||
2. Dictionary comparison, hence false.
|
||||
2. Dictionary comparison, hence false. `"a"` is smaller than `"p"`.
|
||||
3. Again, dictionary comparison, first char of `"2"` is greater than the first char of `"1"`.
|
||||
4. Values `null` and `undefined` equal each other only.
|
||||
5. Strict equality is strict. Different types from both sides lead to false.
|
||||
6. See (4).
|
||||
6. Similar to `(4)`, `null` only equals `undefined`.
|
||||
7. Strict equality of different types.
|
||||
|
|
|
@ -4,7 +4,7 @@ importance: 5
|
|||
|
||||
# Comparisons
|
||||
|
||||
What will be the result for expressions?
|
||||
What will be the result for these expressions?
|
||||
|
||||
```js no-beautify
|
||||
5 > 4
|
||||
|
|
|
@ -1,18 +1,18 @@
|
|||
# Comparisons
|
||||
|
||||
Many comparison operators we know from maths:
|
||||
We know many comparison operators from maths:
|
||||
|
||||
- Greater/less than: <code>a > b</code>, <code>a < b</code>.
|
||||
- Greater/less than or equals: <code>a >= b</code>, <code>a <= b</code>.
|
||||
- Equality check is written as `a == b` (please note the double equation sign `=`. A single symbol `a = b` would mean an assignment).
|
||||
- Not equals. In maths the notation is <code>≠</code>, in JavaScript it's written as an assignment with an exclamation sign before it: <code>a != b</code>.
|
||||
- Equals: `a == b` (please note the double equals sign `=`. A single symbol `a = b` would mean an assignment).
|
||||
- Not equals. In maths the notation is <code>≠</code>, but in JavaScript it's written as an assignment with an exclamation sign before it: <code>a != b</code>.
|
||||
|
||||
## Boolean is the result
|
||||
|
||||
Just as all other operators, a comparison returns a value. The value is of the boolean type.
|
||||
Like all other operators, a comparison returns a value. In this case, the value is a boolean.
|
||||
|
||||
- `true` -- means "yes", "correct" or "the truth".
|
||||
- `false` -- means "no", "wrong" or "a lie".
|
||||
- `false` -- means "no", "wrong" or "not the truth".
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -31,7 +31,7 @@ alert( result ); // true
|
|||
|
||||
## String comparison
|
||||
|
||||
To see which string is greater than the other, the so-called "dictionary" or "lexicographical" order is used.
|
||||
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.
|
||||
|
||||
|
@ -45,29 +45,27 @@ alert( 'Bee' > 'Be' ); // true
|
|||
|
||||
The algorithm to compare two strings is simple:
|
||||
|
||||
1. Compare first characters of both strings.
|
||||
2. If the first one is greater(or less), then the first string is greater(or less) than the second. We're done.
|
||||
3. Otherwise if first characters are equal, compare the second characters the same way.
|
||||
4. Repeat until the end of any string.
|
||||
5. If both strings ended simultaneously, then they are equal. Otherwise the longer string is greater.
|
||||
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 example above, the comparison `'Z' > 'A'` gets the result at the first step.
|
||||
|
||||
Strings `"Glow"` and `"Glee"` are compared character-by-character:
|
||||
In the examples above, the comparison `'Z' > 'A'` gets to a result at the first step while the strings `"Glow"` and `"Glee"` 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 book dictionaries or phone books. But it's not exactly the same.
|
||||
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? Actually, the lowercase `"a"` is. Why? Because the lowercase character has a greater index in the internal encoding table (Unicode). We'll get back to specific details and consequences in the chapter <info:string>.
|
||||
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 <info:string>.
|
||||
```
|
||||
|
||||
## Comparison of different types
|
||||
|
||||
When compared values belong to different types, they are converted to numbers.
|
||||
When comparing values of different types, JavaScript converts the values to numbers.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -76,7 +74,9 @@ 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`, that's why:
|
||||
For boolean values, `true` becomes `1` and `false` becomes `0`.
|
||||
|
||||
For example:
|
||||
|
||||
```js run
|
||||
alert( true == 1 ); // true
|
||||
|
@ -101,24 +101,24 @@ alert( Boolean(b) ); // true
|
|||
alert(a == b); // true!
|
||||
```
|
||||
|
||||
From JavaScript's standpoint that's quite normal. An equality check converts using the numeric conversion (hence `"0"` becomes `0`), while `Boolean` conversion uses another set of rules.
|
||||
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 differ `0` from `false`:
|
||||
A regular equality check `==` has a problem. It cannot differentiate `0` from `false`:
|
||||
|
||||
```js run
|
||||
alert( 0 == false ); // true
|
||||
```
|
||||
|
||||
The same thing with an empty string:
|
||||
The same thing happens with an empty string:
|
||||
|
||||
```js run
|
||||
alert( '' == false ); // true
|
||||
```
|
||||
|
||||
That's because operands of different types are converted to a number by the equality operator `==`. An empty string, just like `false`, becomes a zero.
|
||||
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`?
|
||||
|
||||
|
@ -132,19 +132,16 @@ Let's try it:
|
|||
alert( 0 === false ); // false, because the types are different
|
||||
```
|
||||
|
||||
There also exists a "strict non-equality" operator `!==`, as an analogy for `!=`.
|
||||
There is also a "strict non-equality" operator `!==` analogous to `!=`.
|
||||
|
||||
The strict equality check operator is a bit longer to write, but makes it obvious what's going on and leaves less space for errors.
|
||||
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
|
||||
|
||||
Let's see more edge cases.
|
||||
|
||||
There's a non-intuitive behavior when `null` or `undefined` are compared with other values.
|
||||
|
||||
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 belongs to a separate type of its own.
|
||||
: These values are different, because each of them is a different type.
|
||||
|
||||
```js run
|
||||
alert( null === undefined ); // false
|
||||
|
@ -158,9 +155,9 @@ For a non-strict check `==`
|
|||
```
|
||||
|
||||
For maths and other comparisons `< > <= >=`
|
||||
: Values `null/undefined` are converted to a number: `null` becomes `0`, while `undefined` becomes `NaN`.
|
||||
: `null/undefined` are converted to numbers: `null` becomes `0`, while `undefined` becomes `NaN`.
|
||||
|
||||
Now let's see funny things that happen when we apply those rules. And, what's more important, how to not fall into a trap with these features.
|
||||
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
|
||||
|
||||
|
@ -172,15 +169,15 @@ alert( null == 0 ); // (2) false
|
|||
alert( null >= 0 ); // (3) *!*true*/!*
|
||||
```
|
||||
|
||||
Yeah, mathematically that's strange. The last result states that "`null` is greater than or equal to zero". Then one of the comparisons above must be correct, but they are both false.
|
||||
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, hence treat it as `0`. That's why (3) `null >= 0` is true and (1) `null > 0` is 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 participate in comparisons at all:
|
||||
The value `undefined` shouldn't be compared to other values:
|
||||
|
||||
```js run
|
||||
alert( undefined > 0 ); // false (1)
|
||||
|
@ -188,25 +185,25 @@ alert( undefined < 0 ); // false (2)
|
|||
alert( undefined == 0 ); // false (3)
|
||||
```
|
||||
|
||||
Why does it dislike a zero so much? Always false!
|
||||
Why does it dislike zero so much? Always false!
|
||||
|
||||
We've got these results because:
|
||||
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` and no other value.
|
||||
- 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.
|
||||
|
||||
### Evade problems
|
||||
|
||||
Why did we observe 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 evade any problems with them.
|
||||
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 evade problems with them:
|
||||
|
||||
Just 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 are really sure what you're doing. If a variable can have such values, then check for them separately.
|
||||
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 logical value.
|
||||
- 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).
|
||||
- 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`. Making a separate check for `null/undefined` is a good idea.
|
||||
- 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.
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
# Interaction: alert, prompt, confirm
|
||||
|
||||
This part of the tutorial aims to cover JavaScript "as is", without environment-specific tweaks.
|
||||
In this part of the tutorial we cover JavaScript language "as is", without environment-specific tweaks.
|
||||
|
||||
But still we use a browser as the demo environment. So we should know at least a few user-interface functions. In this chapter we'll get familiar with the browser functions `alert`, `prompt` and `confirm`.
|
||||
But we'll still be using the browser as our demo environment, so we should know at least a few of its user-interface functions. In this chapter, we'll get familiar with the browser functions `alert`, `prompt` and `confirm`.
|
||||
|
||||
## alert
|
||||
|
||||
|
@ -12,7 +12,7 @@ Syntax:
|
|||
alert(message);
|
||||
```
|
||||
|
||||
This shows a message and pauses the script execution until the user presses "OK".
|
||||
This shows a message and pauses script execution until the user presses "OK".
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -20,27 +20,27 @@ For example:
|
|||
alert("Hello");
|
||||
```
|
||||
|
||||
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".
|
||||
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
|
||||
|
||||
Function `prompt` accepts two arguments:
|
||||
The function `prompt` accepts two arguments:
|
||||
|
||||
```js no-beautify
|
||||
result = prompt(title[, default]);
|
||||
result = prompt(title, [default]);
|
||||
```
|
||||
|
||||
It shows a modal window with a text message, an input field for the visitor and buttons OK/CANCEL.
|
||||
It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.
|
||||
|
||||
`title`
|
||||
: The text to show to the visitor.
|
||||
: The text to show the visitor.
|
||||
|
||||
`default`
|
||||
: An optional second parameter, the initial value for the input field.
|
||||
|
||||
The visitor may type something in the prompt input field and press OK. Or they can cancel the input by pressing the CANCEL button or hitting the `key:Esc` key.
|
||||
The visitor may type something in the prompt input field and press OK. Or they can cancel the input by pressing Cancel or hitting the `key:Esc` key.
|
||||
|
||||
The call to `prompt` returns the text from the field or `null` if the input was canceled.
|
||||
The call to `prompt` returns the text from the input field or `null` if the input was canceled.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -50,16 +50,16 @@ let age = prompt('How old are you?', 100);
|
|||
alert(`You are ${age} years old!`); // You are 100 years old!
|
||||
```
|
||||
|
||||
````warn header="IE: always supply a `default`"
|
||||
The second parameter is optional. But if we don't supply it, Internet Explorer would insert the text `"undefined"` into the prompt.
|
||||
````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 that:
|
||||
Run this code in Internet Explorer to see:
|
||||
|
||||
```js run
|
||||
let test = prompt("Test");
|
||||
```
|
||||
|
||||
So, to look good in IE, it's recommended to always provide the second argument:
|
||||
So, for prompts to look good in IE, we recommend always providing the second argument:
|
||||
|
||||
```js run
|
||||
let test = prompt("Test", ''); // <-- for IE
|
||||
|
@ -74,7 +74,7 @@ The syntax:
|
|||
result = confirm(question);
|
||||
```
|
||||
|
||||
Function `confirm` shows a modal window with a `question` and two buttons: OK and CANCEL.
|
||||
The function `confirm` shows a modal window with a `question` and two buttons: OK and Cancel.
|
||||
|
||||
The result is `true` if OK is pressed and `false` otherwise.
|
||||
|
||||
|
@ -88,22 +88,22 @@ alert( isBoss ); // true if OK is pressed
|
|||
|
||||
## Summary
|
||||
|
||||
We covered 3 browser-specific functions to interact with the visitor:
|
||||
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 or `key:Esc` is clicked, all browsers return `null`.
|
||||
: shows a message asking the user to input text. It returns the text or, if Cancel button or `key:Esc` is clicked, `null`.
|
||||
|
||||
`confirm`
|
||||
: shows a message and waits for the user to press "OK" or "CANCEL". It returns `true` for OK and `false` for CANCEL/`key:Esc`.
|
||||
: shows a message and waits for the user to press "OK" or "Cancel". It returns `true` for OK and `false` for Cancel/`key:Esc`.
|
||||
|
||||
All these methods are modal: they pause the script execution and don't allow the visitor to interact with the rest of the page until the message has been dismissed.
|
||||
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.
|
||||
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.
|
||||
|
|
Before Width: | Height: | Size: 23 KiB |
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="264" viewBox="0 0 500 264"><defs><style>@import url(https://fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic%7CPT+Mono);@font-face{font-family:'PT Mono';font-weight:700;font-style:normal;src:local('PT MonoBold'),url(/font/PTMonoBold.woff2) format('woff2'),url(/font/PTMonoBold.woff) format('woff'),url(/font/PTMonoBold.ttf) format('truetype')}</style></defs><g id="combined" fill="none" fill-rule="evenodd" stroke="none" stroke-width="1"><g id="ifelse_task2.svg"><path id="Path-1218-Copy" fill="#EE6B47" fill-rule="nonzero" d="M425.5 133.5v54h8l-9.5 19-9.5-19h8v-51h-82v-3h85z"/><g id="Rectangle-1-+-Корень" transform="translate(213 4)"><rect id="Rectangle-1" width="78" height="28" x="1" y="1" fill="#FFF9EB" stroke="#E8C48E" stroke-width="2" rx="14"/><text id="Begin" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="21" y="19">Begin</tspan></text></g><g id="Rectangle-1-+-Корень-Copy-2" transform="translate(8 206)"><rect id="Rectangle-1" width="131" height="49" x="1" y="1" fill="#FFF9EB" stroke="#E8C48E" stroke-width="2" rx="24.5"/><text id="You-don't-know?-“ECM" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="13.354" y="20">You don't know?</tspan> <tspan x="21.967" y="39">“ECMAScript”!</tspan></text></g><g id="Rectangle-1-+-Корень-Copy-3" transform="translate(354 206)"><rect id="Rectangle-1" width="131" height="49" x="1" y="1" fill="#FFF9EB" stroke="#E8C48E" stroke-width="2" rx="24.5"/><text id="Right!" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="47.93" y="28">Right!</tspan></text></g><path id="Line" fill="#EE6B47" fill-rule="nonzero" d="M255 34v23.049l8 .001-9.5 19-9.5-19 8-.001V34h3z"/><path id="Path-1218" fill="#EE6B47" fill-rule="nonzero" d="M139.5 133.5v3h-59v51h8l-9.5 19-9.5-19h8v-54h62z"/><path id="Rectangle-356" fill="#FFF" d="M47 152h60v20H47z"/><g id="Rectangle-354-+-Каково-“официальное”" transform="translate(137 76)"><path id="Rectangle-354" fill="#FFF9EB" stroke="#E8C48E" stroke-width="2" d="M2.199 59.5L116.5 117.877 230.801 59.5 116.5 1.123 2.199 59.5z"/><text id="What's-the-“official" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="81.026" y="43">What's the</tspan> <tspan x="60.635" y="62">“official” name of</tspan> <tspan x="80.77" y="81">JavaScript?</tspan></text></g><text id="Other" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="57" y="166">Other</tspan></text><path id="Rectangle-356-Copy" fill="#FFF" d="M387 152h60v20h-60z"/><text id="ECMAScript" fill="#8A704D" font-family="OpenSans-Regular, Open Sans" font-size="14" font-weight="normal"><tspan x="383" y="165">ECMAScript</tspan></text></g></g></svg>
|
After Width: | Height: | Size: 2.9 KiB |
Before Width: | Height: | Size: 56 KiB |
|
@ -8,7 +8,6 @@ Using the `if..else` construct, write the code which asks: 'What is the "officia
|
|||
|
||||
If the visitor enters "ECMAScript", then output "Right!", otherwise -- output: "Didn't know? ECMAScript!"
|
||||
|
||||

|
||||

|
||||
|
||||
[demo src="ifelse_task2"]
|
||||
|
||||
|
|
Before Width: | Height: | Size: 38 KiB |
Before Width: | Height: | Size: 92 KiB |
|
@ -1,6 +1,6 @@
|
|||
|
||||
|
||||
```js
|
||||
result = (a + b < 4) ? 'Below' : 'Over';
|
||||
let result = (a + b < 4) ? 'Below' : 'Over';
|
||||
```
|
||||
|
||||
|
|
|
@ -4,13 +4,14 @@ importance: 5
|
|||
|
||||
# Rewrite 'if' into '?'
|
||||
|
||||
Rewrite this `if` using the ternary operator `'?'`:
|
||||
Rewrite this `if` using the conditional operator `'?'`:
|
||||
|
||||
```js
|
||||
let result;
|
||||
|
||||
if (a + b < 4) {
|
||||
result = 'Below';
|
||||
} else {
|
||||
result = 'Over';
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
# Conditional operators: if, '?'
|
||||
|
||||
Sometimes we need to perform different actions based on a condition.
|
||||
Sometimes, we need to perform different actions based on different conditions.
|
||||
|
||||
There is the `if` statement for that and also the conditional (ternary) operator for conditional evaluation which we will be referring as the “question mark” operator `?` for simplicity.
|
||||
To do that, we can use the `if` statement and the conditional operator `?`, that's also called a "question mark" operator.
|
||||
|
||||
## The "if" statement
|
||||
|
||||
The `if` statement gets a condition, evaluates it and, if the result is `true`, executes the code.
|
||||
The `if(...)` statement evaluates a condition in parentheses and, if the result is `true`, executes a block of code.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -18,9 +18,9 @@ if (year == 2015) alert( 'You are right!' );
|
|||
*/!*
|
||||
```
|
||||
|
||||
In the example above, the condition is a simple equality check: `year == 2015`, but it can be much more complex.
|
||||
In the example above, the condition is a simple equality check (`year == 2015`), but it can be much more complex.
|
||||
|
||||
If there is more than one statement to be executed, we have to wrap our code block inside curly braces:
|
||||
If we want to execute more than one statement, we have to wrap our code block inside curly braces:
|
||||
|
||||
```js
|
||||
if (year == 2015) {
|
||||
|
@ -29,15 +29,15 @@ if (year == 2015) {
|
|||
}
|
||||
```
|
||||
|
||||
It is recommended to wrap your code block with curly braces `{}` every time with `if`, even if there is only one statement. That improves readability.
|
||||
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.
|
||||
|
||||
## Boolean conversion
|
||||
|
||||
The `if (…)` statement evaluates the expression in parentheses and converts it to the boolean type.
|
||||
The `if (…)` statement evaluates the expression in its parentheses and converts the result to a boolean.
|
||||
|
||||
Let's recall the conversion rules from the chapter <info:type-conversions>:
|
||||
|
||||
- A number `0`, an empty string `""`, `null`, `undefined` and `NaN` become `false`. Because of that they are called "falsy" values.
|
||||
- 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".
|
||||
|
||||
So, the code under this condition would never execute:
|
||||
|
@ -48,7 +48,7 @@ if (0) { // 0 is falsy
|
|||
}
|
||||
```
|
||||
|
||||
...And inside this condition -- always works:
|
||||
...and inside this condition -- it always will:
|
||||
|
||||
```js
|
||||
if (1) { // 1 is truthy
|
||||
|
@ -56,7 +56,7 @@ if (1) { // 1 is truthy
|
|||
}
|
||||
```
|
||||
|
||||
We can also pass a pre-evaluated boolean value to `if`, like here:
|
||||
We can also pass a pre-evaluated boolean value to `if`, like this:
|
||||
|
||||
```js
|
||||
let cond = (year == 2015); // equality evaluates to true or false
|
||||
|
@ -68,11 +68,11 @@ if (cond) {
|
|||
|
||||
## The "else" clause
|
||||
|
||||
The `if` statement may contain an optional "else" block. It executes when the condition is wrong.
|
||||
The `if` statement may contain an optional "else" block. It executes when the condition is false.
|
||||
|
||||
For example:
|
||||
```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 +83,12 @@ if (year == 2015) {
|
|||
|
||||
## Several conditions: "else if"
|
||||
|
||||
Sometimes we'd like to test several variants of a condition. There is an `else if` clause for that.
|
||||
Sometimes, we'd like to test several variants of a condition. The `else if` clause lets us do that.
|
||||
|
||||
For example:
|
||||
|
||||
```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,13 +99,13 @@ if (year < 2015) {
|
|||
}
|
||||
```
|
||||
|
||||
In the code above JavaScript first checks `year < 2015`. If it is falsy it then goes to the next condition `year > 2015`, and otherwise shows the last `alert`.
|
||||
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 ending `else` is optional.
|
||||
There can be more `else if` blocks. The final `else` is optional.
|
||||
|
||||
## Ternary operator '?'
|
||||
## Conditional operator '?'
|
||||
|
||||
Sometimes we need to assign a variable depending on a condition.
|
||||
Sometimes, we need to assign a variable depending on a condition.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -124,16 +124,16 @@ if (age > 18) {
|
|||
alert(accessAllowed);
|
||||
```
|
||||
|
||||
The so-called "ternary" or "question mark" operator lets us do that shorter and simpler.
|
||||
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 `?`. The formal term "ternary" means that the operator has three operands. It is actually the one and only operator in JavaScript which has that many.
|
||||
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.
|
||||
|
||||
The syntax is:
|
||||
```js
|
||||
let result = condition ? value1 : value2
|
||||
let result = condition ? value1 : value2;
|
||||
```
|
||||
|
||||
The `condition` is evaluated, if it's truthy then `value1` is returned, otherwise -- `value2`.
|
||||
The `condition` is evaluated: if it's truthy then `value1` is returned, otherwise -- `value2`.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -141,7 +141,9 @@ For example:
|
|||
let accessAllowed = (age > 18) ? true : false;
|
||||
```
|
||||
|
||||
Technically, we can omit parentheses around `age > 18`. The question mark operator has a low precedence. It executes after the comparison `>`, so that'll do the same:
|
||||
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:
|
||||
|
||||
```js
|
||||
// the comparison operator "age > 18" executes first anyway
|
||||
|
@ -149,10 +151,10 @@ Technically, we can omit parentheses around `age > 18`. The question mark operat
|
|||
let accessAllowed = age > 18 ? true : false;
|
||||
```
|
||||
|
||||
But parentheses make the code more readable, so it's recommended to use them.
|
||||
But parentheses make the code more readable, so we recommend using them.
|
||||
|
||||
````smart
|
||||
In the example above it's possible to evade the question mark operator, because the comparison by itself returns `true/false`:
|
||||
In the example above, you can avoid using the question mark operator because the comparison itself returns `true/false`:
|
||||
|
||||
```js
|
||||
// the same
|
||||
|
@ -162,7 +164,7 @@ let accessAllowed = age > 18;
|
|||
|
||||
## Multiple '?'
|
||||
|
||||
A sequence of question mark `?` operators allows returning a value that depends on more than one condition.
|
||||
A sequence of question mark operators `?` can return a value that depends on more than one condition.
|
||||
|
||||
For instance:
|
||||
```js run
|
||||
|
@ -176,14 +178,14 @@ let message = (age < 3) ? 'Hi, baby!' :
|
|||
alert( message );
|
||||
```
|
||||
|
||||
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.
|
||||
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 -- returns `'Hi, baby!'`, otherwise -- goes after the colon `":"` and checks for `age < 18`.
|
||||
3. If that's true -- returns `'Hello!'`, otherwise -- goes after the next colon `":"` and checks for `age < 100`.
|
||||
4. If that's true -- returns `'Greetings!'`, otherwise -- goes after the last colon `":"` and returns `'What an unusual age!'`.
|
||||
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!'`.
|
||||
|
||||
The same logic using `if..else`:
|
||||
Here's how this looks using `if..else`:
|
||||
|
||||
```js
|
||||
if (age < 3) {
|
||||
|
@ -210,15 +212,15 @@ let company = prompt('Which company created JavaScript?', '');
|
|||
*/!*
|
||||
```
|
||||
|
||||
Depending on the condition `company == 'Netscape'`, either the first or the second part after `?` gets executed and shows the alert.
|
||||
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. The idea is to execute different code depending on the condition.
|
||||
We don't assign a result to a variable here. Instead, we execute different code depending on the condition.
|
||||
|
||||
**It is not recommended to use the question mark operator in this way.**
|
||||
**It's not recommended to use the question mark operator in this way.**
|
||||
|
||||
The notation seems to be shorter than `if`, which appeals to some programmers. But it is less readable.
|
||||
The notation is shorter than the equivalent `if` statement, which appeals to some programmers. But it is less readable.
|
||||
|
||||
Here is the same code with `if` for comparison:
|
||||
Here is the same code using `if` for comparison:
|
||||
|
||||
```js run no-beautify
|
||||
let company = prompt('Which company created JavaScript?', '');
|
||||
|
@ -232,6 +234,6 @@ if (company == 'Netscape') {
|
|||
*/!*
|
||||
```
|
||||
|
||||
Our eyes scan the code vertically. The constructs which span several lines are easier to understand than a long horizontal instruction set.
|
||||
Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.
|
||||
|
||||
The idea of a question mark `?` is to return one or another value depending on the condition. Please use it for exactly that. There is `if` to execute different branches of the code.
|
||||
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.
|
||||
|
|
|
@ -4,7 +4,7 @@ importance: 5
|
|||
|
||||
# What's the result of OR?
|
||||
|
||||
What the code below is going to output?
|
||||
What is the code below going to output?
|
||||
|
||||
```js
|
||||
alert( null || 2 || undefined );
|
||||
|
|
|
@ -4,7 +4,7 @@ importance: 3
|
|||
|
||||
# What's the result of OR'ed alerts?
|
||||
|
||||
What the code below will output?
|
||||
What will the code below output?
|
||||
|
||||
```js
|
||||
alert( alert(1) || 2 || alert(3) );
|
||||
|
|
|
@ -4,7 +4,7 @@ importance: 5
|
|||
|
||||
# What is the result of AND?
|
||||
|
||||
What this code is going to show?
|
||||
What is this code going to show?
|
||||
|
||||
```js
|
||||
alert( 1 && null && 2 );
|
||||
|
|
|
@ -12,5 +12,5 @@ The result of `2 && 3 = 3`, so the expression becomes:
|
|||
null || 3 || 4
|
||||
```
|
||||
|
||||
Now the result if the first truthy value: `3`.
|
||||
Now the result is the first truthy value: `3`.
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ importance: 5
|
|||
|
||||
# The result of OR AND OR
|
||||
|
||||
What will be the result?
|
||||
What will the result be?
|
||||
|
||||
```js
|
||||
alert( null || 2 && 3 || 4 );
|
||||
|
|
|
@ -6,7 +6,7 @@ importance: 5
|
|||
|
||||
Which of these `alert`s are going to execute?
|
||||
|
||||
What will be the results of the expressions inside `if(...)`?
|
||||
What will the results of the expressions be inside `if(...)`?
|
||||
|
||||
```js
|
||||
if (-1 || 0) alert( 'first' );
|
||||
|
|
After Width: | Height: | Size: 6 KiB |
|
@ -10,7 +10,7 @@ if (userName == 'Admin') {
|
|||
if (pass == 'TheMaster') {
|
||||
alert( 'Welcome!' );
|
||||
} else if (pass == '' || pass == null) {
|
||||
alert( 'Canceled.' );
|
||||
alert( 'Canceled' );
|
||||
} else {
|
||||
alert( 'Wrong password' );
|
||||
}
|
|
@ -6,20 +6,20 @@ importance: 3
|
|||
|
||||
Write the code which asks for a login with `prompt`.
|
||||
|
||||
If the visitor enters `"Admin"`, then `prompt` for a password, if the input is an empty line or `key:Esc` -- show "Canceled.", if it's another string -- then show "I don't know you".
|
||||
If the visitor enters `"Admin"`, then `prompt` for a password, if the input is an empty line or `key:Esc` -- show "Canceled", if it's another string -- then show "I don't know you".
|
||||
|
||||
The password is checked as follows:
|
||||
|
||||
- If it equals "TheMaster", then show "Welcome!",
|
||||
- Another string -- show "Wrong password",
|
||||
- For an empty string or cancelled input, show "Canceled."
|
||||
- For an empty string or cancelled input, show "Canceled"
|
||||
|
||||
The schema:
|
||||
|
||||

|
||||

|
||||
|
||||
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`.
|
||||
Hint: passing an empty input to a prompt returns an empty string `''`. Pressing `key:ESC` during a prompt returns `null`.
|
||||
|
||||
[demo]
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
There are three logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT).
|
||||
|
||||
Although they are called "logical", they can be applied to values of any type, not only boolean. The result can also be of any type.
|
||||
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.
|
||||
|
||||
Let's see the details.
|
||||
|
||||
|
@ -14,9 +14,9 @@ The "OR" operator is represented with two vertical line symbols:
|
|||
result = a || b;
|
||||
```
|
||||
|
||||
In classical programming, logical OR is meant to manipulate boolean values only. If any of its arguments are `true`, then it returns `true`, otherwise it returns `false`.
|
||||
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 more tricky and powerful. But first let's see what happens with boolean values.
|
||||
In JavaScript, the operator is a little bit trickier and more powerful. But first, let's see what happens with boolean values.
|
||||
|
||||
There are four possible logical combinations:
|
||||
|
||||
|
@ -29,9 +29,9 @@ alert( false || false ); // false
|
|||
|
||||
As we can see, the result is always `true` except for the case when both operands are `false`.
|
||||
|
||||
If an operand is not boolean, then it's converted to boolean for the evaluation.
|
||||
If an operand is not a boolean, it's converted to a boolean for the evaluation.
|
||||
|
||||
For instance, a number `1` is treated as `true`, a number `0` -- as `false`:
|
||||
For instance, the number `1` is treated as `true`, the number `0` as `false`:
|
||||
|
||||
```js run
|
||||
if (1 || 0) { // works just like if( true || false )
|
||||
|
@ -39,7 +39,7 @@ if (1 || 0) { // works just like if( true || false )
|
|||
}
|
||||
```
|
||||
|
||||
Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is correct.
|
||||
Most of the time, OR `||` is used in an `if` statement to test if *any* of the given conditions is `true`.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -64,9 +64,9 @@ if (hour < 10 || hour > 18 || isWeekend) {
|
|||
}
|
||||
```
|
||||
|
||||
## OR seeks the first truthy value
|
||||
## OR "||" finds the first truthy value
|
||||
|
||||
The logic described above is somewhat classical. Now let's bring in the "extra" features of JavaScript.
|
||||
The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript.
|
||||
|
||||
The extended algorithm works as follows.
|
||||
|
||||
|
@ -78,13 +78,13 @@ result = value1 || value2 || value3;
|
|||
|
||||
The OR `||` operator does the following:
|
||||
|
||||
- Evaluate operands from left to right.
|
||||
- For each operand, convert it to boolean. If the result is `true`, then stop and return the original value of that operand.
|
||||
- If all other operands have been assessed (i.e. all were `false`), return the last operand.
|
||||
- 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.
|
||||
|
||||
A value is returned in its original form, without the conversion.
|
||||
|
||||
In other words, a chain of OR `"||"` returns the first truthy value or the last one if no such value is found.
|
||||
In other words, a chain of OR `"||"` returns the first truthy value or the last one if no truthy value is found.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -97,13 +97,13 @@ alert( null || 0 || 1 ); // 1 (the first truthy value)
|
|||
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
|
||||
```
|
||||
|
||||
That leads to some interesting usages compared to a "pure, classical, boolean-only OR".
|
||||
This leads to some interesting usage compared to a "pure, classical, boolean-only OR".
|
||||
|
||||
1. **Getting the first truthy value from the list of variables or expressions.**
|
||||
1. **Getting the first truthy value from a list of variables or expressions.**
|
||||
|
||||
Imagine we have several variables, which can either contain the data or be `null/undefined`. And we need to choose the first one with data.
|
||||
Imagine we have a list of variables which can either contain data or be `null/undefined`. How can we find the first one with data?
|
||||
|
||||
We can use OR `||` for that:
|
||||
We can use OR `||`:
|
||||
|
||||
```js run
|
||||
let currentUser = null;
|
||||
|
@ -116,14 +116,14 @@ That leads to some interesting usages compared to a "pure, classical, boolean-on
|
|||
alert( name ); // selects "John" – the first truthy value
|
||||
```
|
||||
|
||||
If both `currentUser` and `defaultUser` were falsy then `"unnamed"` would be the result.
|
||||
If both `currentUser` and `defaultUser` were falsy, `"unnamed"` would be the result.
|
||||
2. **Short-circuit evaluation.**
|
||||
|
||||
Operands can be not only values, but arbitrary expressions. OR evaluates and tests them from left to right. The evaluation stops when a truthy value is reached, and the value is returned. The process is called "a short-circuit evaluation", because it goes as short as possible from left to right.
|
||||
Operands can be not only values, but arbitrary expressions. OR evaluates and tests them from left to right. The evaluation stops when a truthy value is reached, and the value is returned. This process is called "a short-circuit evaluation" because it goes as short as possible from left to right.
|
||||
|
||||
This is clearly seen when the expression given as the second argument has a side effect. Like a variable assignment.
|
||||
This is clearly seen when the expression given as the second argument has a side effect like a variable assignment.
|
||||
|
||||
If we run the example below, `x` would not get assigned:
|
||||
In the example below, `x` does not get assigned:
|
||||
|
||||
```js run no-beautify
|
||||
let x;
|
||||
|
@ -133,7 +133,7 @@ That leads to some interesting usages compared to a "pure, classical, boolean-on
|
|||
alert(x); // undefined, because (x = 1) not evaluated
|
||||
```
|
||||
|
||||
...And if the first argument is `false`, then `OR` goes on and evaluates the second one thus running the assignment:
|
||||
If, instead, the first argument is `false`, `||` evaluates the second one, thus running the assignment:
|
||||
|
||||
```js run no-beautify
|
||||
let x;
|
||||
|
@ -143,11 +143,11 @@ That leads to some interesting usages compared to a "pure, classical, boolean-on
|
|||
alert(x); // 1
|
||||
```
|
||||
|
||||
An assignment is a simple case, other side effects can be involved.
|
||||
An assignment is a simple case. There may be side effects, that won't show up if the evaluation doesn't reach them.
|
||||
|
||||
As we can see, such a use case is a "shorter way to do `if`". The first operand is converted to boolean and if it's false then the second one is evaluated.
|
||||
As we can see, such a use case is a "shorter way of doing `if`". The first operand is converted to boolean. If it's false, the second one is evaluated.
|
||||
|
||||
Most of time it's better to use a "regular" `if` to keep the code easy to understand, but sometimes that can be handy.
|
||||
Most of time, it's better to use a "regular" `if` to keep the code easy to understand, but sometimes this can be handy.
|
||||
|
||||
## && (AND)
|
||||
|
||||
|
@ -157,7 +157,7 @@ The AND operator is represented with two ampersands `&&`:
|
|||
result = a && b;
|
||||
```
|
||||
|
||||
In classical programming AND returns `true` if both operands are truthy and `false` otherwise:
|
||||
In classical programming, AND returns `true` if both operands are truthy and `false` otherwise:
|
||||
|
||||
```js run
|
||||
alert( true && true ); // true
|
||||
|
@ -173,11 +173,11 @@ let hour = 12;
|
|||
let minute = 30;
|
||||
|
||||
if (hour == 12 && minute == 30) {
|
||||
alert( 'Time is 12:30' );
|
||||
alert( 'The time is 12:30' );
|
||||
}
|
||||
```
|
||||
|
||||
Just as for OR, any value is allowed as an operand of AND:
|
||||
Just as with OR, any value is allowed as an operand of AND:
|
||||
|
||||
```js run
|
||||
if (1 && 0) { // evaluated as true && false
|
||||
|
@ -186,7 +186,7 @@ if (1 && 0) { // evaluated as true && false
|
|||
```
|
||||
|
||||
|
||||
## AND seeks the first falsy value
|
||||
## AND "&&" finds the first falsy value
|
||||
|
||||
Given multiple AND'ed values:
|
||||
|
||||
|
@ -196,9 +196,9 @@ result = value1 && value2 && value3;
|
|||
|
||||
The AND `&&` operator does the following:
|
||||
|
||||
- Evaluate operands from left to right.
|
||||
- For each operand, convert it to a boolean. If the result is `false`, stop and return the original value of that operand.
|
||||
- If all other operands have been assessed (i.e. all were truthy), return the last operand.
|
||||
- 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.
|
||||
|
||||
In other words, AND returns the first falsy value or the last value if none were found.
|
||||
|
||||
|
@ -233,7 +233,7 @@ alert( 1 && 2 && 3 ); // 3, the last one
|
|||
````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 `&&` were in parentheses: `(a && b) || (c && d)`.
|
||||
So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`.
|
||||
````
|
||||
|
||||
Just like OR, the AND `&&` operator can sometimes replace `if`.
|
||||
|
@ -246,7 +246,7 @@ let x = 1;
|
|||
(x > 0) && alert( 'Greater than zero!' );
|
||||
```
|
||||
|
||||
The action in the right part of `&&` would execute only if the evaluation reaches it. That is: only if `(x > 0)` is true.
|
||||
The action in the right part of `&&` would execute only if the evaluation reaches it. That is, only if `(x > 0)` is true.
|
||||
|
||||
So we basically have an analogue for:
|
||||
|
||||
|
@ -258,9 +258,9 @@ if (x > 0) {
|
|||
}
|
||||
```
|
||||
|
||||
The variant with `&&` appears to be shorter. But `if` is more obvious and tends to be a little bit more readable.
|
||||
The variant with `&&` appears shorter. But `if` is more obvious and tends to be a little bit more readable.
|
||||
|
||||
So it is recommended to use every construct for its purpose. Use `if` if we want if. And use `&&` if we want AND.
|
||||
So we recommend using every construct for its purpose: use `if` if we want if and use `&&` if we want AND.
|
||||
|
||||
## ! (NOT)
|
||||
|
||||
|
@ -275,7 +275,7 @@ result = !value;
|
|||
The operator accepts a single argument and does the following:
|
||||
|
||||
1. Converts the operand to boolean type: `true/false`.
|
||||
2. Returns an inverse value.
|
||||
2. Returns the inverse value.
|
||||
|
||||
For instance:
|
||||
|
||||
|
@ -291,7 +291,7 @@ alert( !!"non-empty string" ); // true
|
|||
alert( !!null ); // false
|
||||
```
|
||||
|
||||
That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. At the end we have a plain value-to-boolean conversion.
|
||||
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.
|
||||
|
||||
There's a little more verbose way to do the same thing -- a built-in `Boolean` function:
|
||||
|
||||
|
@ -300,4 +300,4 @@ alert( Boolean("non-empty string") ); // true
|
|||
alert( Boolean(null) ); // false
|
||||
```
|
||||
|
||||
The precedence of NOT `!` is the highest of all bitwise operators, so it always executes first, before any `&&`, `||`.
|
||||
The precedence of NOT `!` is the highest of all logical operators, so it always executes first, before `&&` or `||`.
|
||||
|
|
|
@ -7,11 +7,11 @@ The task demonstrates how postfix/prefix forms can lead to different results whe
|
|||
while (++i < 5) alert( i );
|
||||
```
|
||||
|
||||
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`.
|
||||
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.
|
||||
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.
|
||||
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**
|
||||
|
||||
```js run
|
||||
|
@ -19,12 +19,12 @@ The task demonstrates how postfix/prefix forms can lead to different results whe
|
|||
while (i++ < 5) alert( i );
|
||||
```
|
||||
|
||||
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`).
|
||||
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`.
|
||||
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…`
|
||||
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`.
|
||||
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.
|
||||
The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false.
|
||||
|
|
|
@ -2,11 +2,11 @@ importance: 4
|
|||
|
||||
---
|
||||
|
||||
# Which values shows the while?
|
||||
# Which values does the while loop show?
|
||||
|
||||
For every loop, write down which values it shows, in your opinion. And then compare with the answer.
|
||||
For every loop iteration, write down which value it outputs and then compare it with the solution.
|
||||
|
||||
Both loops `alert` same values or not?
|
||||
Both loops `alert` the same values, or not?
|
||||
|
||||
1. The prefix form `++i`:
|
||||
|
||||
|
|
|
@ -26,4 +26,4 @@ for (let i = 2; i <= n; i++) { // for each i...
|
|||
}
|
||||
```
|
||||
|
||||
There's a lot of space to opimize 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 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.
|
||||
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.
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# Loops: while and for
|
||||
|
||||
We often have a need to perform similar actions many times in a row.
|
||||
We often need to repeat actions.
|
||||
|
||||
For example, when we need to output goods from a list one after another. Or just run the same code for each number from 1 to 10.
|
||||
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 part of code multiple times.
|
||||
*Loops* are a way to repeat the same code multiple times.
|
||||
|
||||
## The "while" loop
|
||||
|
||||
|
@ -17,7 +17,7 @@ while (condition) {
|
|||
}
|
||||
```
|
||||
|
||||
While the `condition` is `true`, the `code` from the loop body is executed.
|
||||
While the `condition` is truthy, the `code` from the loop body is executed.
|
||||
|
||||
For instance, the loop below outputs `i` while `i < 3`:
|
||||
|
||||
|
@ -31,11 +31,11 @@ while (i < 3) { // shows 0, then 1, then 2
|
|||
|
||||
A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations.
|
||||
|
||||
If there were no `i++` in the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and for server-side JavaScript we can kill the process.
|
||||
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 a variable can be a loop condition, not just a comparison. They are evaluated and converted to a boolean by `while`.
|
||||
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, the shorter way to write `while (i != 0)` could be `while (i)`:
|
||||
For instance, a shorter way to write `while (i != 0)` is `while (i)`:
|
||||
|
||||
```js run
|
||||
let i = 3;
|
||||
|
@ -47,8 +47,8 @@ while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
|
|||
}
|
||||
```
|
||||
|
||||
````smart header="Brackets are not required for a single-line body"
|
||||
If the loop body has a single statement, we can omit the brackets `{…}`:
|
||||
````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 `{…}`:
|
||||
|
||||
```js run
|
||||
let i = 3;
|
||||
|
@ -68,7 +68,7 @@ do {
|
|||
} while (condition);
|
||||
```
|
||||
|
||||
The loop will first execute the body, then check the condition and, while it's truthy, execute it again and again.
|
||||
The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again.
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -80,11 +80,11 @@ do {
|
|||
} while (i < 3);
|
||||
```
|
||||
|
||||
This form of syntax is rarely used except 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(…) {…}`.
|
||||
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 the most often used one.
|
||||
The `for` loop is more complex, but it's also the most commonly used loop.
|
||||
|
||||
It looks like this:
|
||||
|
||||
|
@ -102,17 +102,17 @@ for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
|
|||
}
|
||||
```
|
||||
|
||||
Let's examine the `for` statement part by part:
|
||||
Let's examine the `for` statement part-by-part:
|
||||
|
||||
| part | | |
|
||||
|-------|----------|----------------------------------------------------------------------------|
|
||||
| begin | `i = 0` | Executes once upon entering the loop. |
|
||||
| condition | `i < 3`| Checked before every loop iteration, if fails the loop stops. |
|
||||
| step| `i++` | Executes after the body on each iteration, but before the condition check. |
|
||||
| body | `alert(i)`| Runs again and again while the condition is truthy |
|
||||
|
||||
| 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)
|
||||
|
@ -121,9 +121,11 @@ Run begin
|
|||
→ ...
|
||||
```
|
||||
|
||||
If you are new to loops, then maybe it would help if you go back to the example and reproduce how it runs step-by-step on a piece of paper.
|
||||
That is, `begin` executes once, and then it iterates: after each `condition` test, `body` and `step` are executed.
|
||||
|
||||
Here's what exactly happens in our case:
|
||||
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:
|
||||
|
||||
```js
|
||||
// for (let i = 0; i < 3; i++) alert(i)
|
||||
|
@ -140,7 +142,7 @@ if (i < 3) { alert(i); i++ }
|
|||
```
|
||||
|
||||
````smart header="Inline variable declaration"
|
||||
Here the "counter" variable `i` is declared right in the loop. That's called an "inline" variable declaration. Such variables are visible only inside the loop.
|
||||
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.
|
||||
|
||||
```js run
|
||||
for (*!*let*/!* i = 0; i < 3; i++) {
|
||||
|
@ -149,7 +151,7 @@ for (*!*let*/!* i = 0; i < 3; i++) {
|
|||
alert(i); // error, no such variable
|
||||
```
|
||||
|
||||
Instead of defining a variable, we can use an existing one:
|
||||
Instead of defining a variable, we could use an existing one:
|
||||
|
||||
```js run
|
||||
let i = 0;
|
||||
|
@ -190,9 +192,9 @@ for (; i < 3;) {
|
|||
}
|
||||
```
|
||||
|
||||
The loop became identical to `while (i < 3)`.
|
||||
This makes the loop identical to `while (i < 3)`.
|
||||
|
||||
We can actually remove everything, thus creating an infinite loop:
|
||||
We can actually remove everything, creating an infinite loop:
|
||||
|
||||
```js
|
||||
for (;;) {
|
||||
|
@ -200,17 +202,17 @@ for (;;) {
|
|||
}
|
||||
```
|
||||
|
||||
Please note that the two `for` semicolons `;` must be present, otherwise it would be a syntax error.
|
||||
Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error.
|
||||
|
||||
## Breaking the loop
|
||||
|
||||
Normally the loop exits when the condition becomes falsy.
|
||||
Normally, a loop exits when its condition becomes falsy.
|
||||
|
||||
But we can force the exit at any moment. There's a special `break` directive for that.
|
||||
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, but "breaks" when no number is entered:
|
||||
For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered:
|
||||
|
||||
```js
|
||||
```js run
|
||||
let sum = 0;
|
||||
|
||||
while (true) {
|
||||
|
@ -227,15 +229,15 @@ while (true) {
|
|||
alert( 'Sum: ' + sum );
|
||||
```
|
||||
|
||||
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 the control to the first line after the loop. Namely, `alert`.
|
||||
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 the condition must be checked not in the beginning/end of the loop, but in the middle, or even in several places of the body.
|
||||
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).
|
||||
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 on the current iteration and would like to move on to the next.
|
||||
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:
|
||||
|
||||
|
@ -249,9 +251,9 @@ for (let i = 0; i < 10; i++) {
|
|||
}
|
||||
```
|
||||
|
||||
For even values of `i` the `continue` directive stops body execution, passing the control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values.
|
||||
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 directive `continue` helps to decrease nesting level"
|
||||
````smart header="The `continue` directive helps decrease nesting"
|
||||
A loop that shows odd values could look like this:
|
||||
|
||||
```js
|
||||
|
@ -264,13 +266,13 @@ for (let i = 0; i < 10; i++) {
|
|||
}
|
||||
```
|
||||
|
||||
From a technical point of view it's identical to the example above. Surely, we can just wrap the code in the `if` block instead of `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 we got one more nesting level (the `alert` call inside the curly braces). If the code inside `if` is longer than a few lines, that may decrease the overall readability.
|
||||
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` are disallowed there.
|
||||
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:
|
||||
|
||||
|
@ -282,24 +284,23 @@ if (i > 5) {
|
|||
}
|
||||
```
|
||||
|
||||
...And rewrite it using a question mark:
|
||||
...and rewrite it using a question mark:
|
||||
|
||||
|
||||
```js no-beautify
|
||||
(i > 5) ? alert(i) : *!*continue*/!*; // continue not allowed here
|
||||
(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here
|
||||
```
|
||||
|
||||
...Then it stops working. The code like this will give a syntax error:
|
||||
...it stops working: there's a syntax error.
|
||||
|
||||
|
||||
That's just another reason not to use a question mark operator `?` instead of `if`.
|
||||
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 coordinates `(i, j)` from `(0,0)` to `(3,3)`:
|
||||
For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(2,2)`:
|
||||
|
||||
```js run no-beautify
|
||||
for (let i = 0; i < 3; i++) {
|
||||
|
@ -308,8 +309,7 @@ for (let i = 0; i < 3; i++) {
|
|||
|
||||
let input = prompt(`Value at coords (${i},${j})`, '');
|
||||
|
||||
// what if I want to exit from here to Done (below)?
|
||||
|
||||
// what if we want to exit from here to Done (below)?
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -318,7 +318,7 @@ alert('Done!');
|
|||
|
||||
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.
|
||||
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:
|
||||
```js
|
||||
|
@ -327,9 +327,7 @@ labelName: for (...) {
|
|||
}
|
||||
```
|
||||
|
||||
The `break <labelName>` statement in the loop breaks out to the label.
|
||||
|
||||
Like here:
|
||||
The `break <labelName>` statement in the loop below breaks out to the label:
|
||||
|
||||
```js run no-beautify
|
||||
*!*outer:*/!* for (let i = 0; i < 3; i++) {
|
||||
|
@ -347,7 +345,7 @@ Like here:
|
|||
alert('Done!');
|
||||
```
|
||||
|
||||
In the code above `break outer` looks upwards for the label named `outer` and breaks out of that loop.
|
||||
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!')`.
|
||||
|
||||
|
@ -358,19 +356,19 @@ outer:
|
|||
for (let i = 0; i < 3; i++) { ... }
|
||||
```
|
||||
|
||||
The `continue` directive can also be used with a label. In this case the execution jumps to the next iteration of the labeled loop.
|
||||
The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop.
|
||||
|
||||
````warn header="Labels are not a \"goto\""
|
||||
Labels do not allow us to jump into an arbitrary place of code.
|
||||
````warn header="Labels do not allow to \"jump\" anywhere"
|
||||
Labels do not allow us to jump into an arbitrary place in the code.
|
||||
|
||||
For example, it is impossible to do this:
|
||||
```js
|
||||
break label; // jumps to label? No.
|
||||
break label; // doesn't jumps to the label below
|
||||
|
||||
label: for (...)
|
||||
```
|
||||
|
||||
The call to a `break/continue` is only possible from inside the loop, and the label must be somewhere upwards from the directive.
|
||||
A call to `break/continue` is only possible from inside a loop and the label must be somewhere above the directive.
|
||||
````
|
||||
|
||||
## Summary
|
||||
|
@ -383,6 +381,6 @@ We covered 3 types of loops:
|
|||
|
||||
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 on the current iteration and would like to forward to the next one, the `continue` directive does it.
|
||||
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 the nesting and go to the outer loop.
|
||||
`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.
|
||||
|
|
|
@ -125,7 +125,7 @@ switch (a) {
|
|||
break;
|
||||
|
||||
*!*
|
||||
case 3: // (*) grouped two cases
|
||||
case 3: // (*) grouped two cases
|
||||
case 5:
|
||||
alert('Wrong!');
|
||||
alert("Why don't you take a math class?");
|
||||
|
@ -148,7 +148,7 @@ Let's emphasize that the equality check is always strict. The values must be of
|
|||
For example, let's consider the code:
|
||||
|
||||
```js run
|
||||
let arg = prompt("Enter a value?")
|
||||
let arg = prompt("Enter a value?");
|
||||
switch (arg) {
|
||||
case '0':
|
||||
case '1':
|
||||
|
@ -163,7 +163,7 @@ switch (arg) {
|
|||
alert( 'Never executes!' );
|
||||
break;
|
||||
default:
|
||||
alert( 'An unknown value' )
|
||||
alert( 'An unknown value' );
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@ function checkAge(age) {
|
|||
if (age > 18) {
|
||||
return true;
|
||||
} else {
|
||||
return confirm('Do you have your parents permission to access this page?');
|
||||
return confirm('Did parents allow you?');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
@ -14,10 +14,8 @@ let x = prompt("x?", '');
|
|||
let n = prompt("n?", '');
|
||||
|
||||
if (n < 1) {
|
||||
alert(`Power ${n} is not supported,
|
||||
use an integer greater than 0`);
|
||||
alert(`Power ${n} is not supported, use a positive integer`);
|
||||
} else {
|
||||
alert( pow(x, n) );
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -20,9 +20,13 @@ function showMessage() {
|
|||
}
|
||||
```
|
||||
|
||||
The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (empty in the example above) and finally the code of the function, also named "the function body", between curly braces.
|
||||
The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (comma-separated, empty in the example above) and finally the code of the function, also named "the function body", between curly braces.
|
||||
|
||||

|
||||
```js
|
||||
function name(parameters) {
|
||||
...body...
|
||||
}
|
||||
```
|
||||
|
||||
Our new function can be called by its name: `showMessage()`.
|
||||
|
||||
|
@ -101,7 +105,7 @@ showMessage();
|
|||
alert( userName ); // *!*Bob*/!*, the value was modified by the function
|
||||
```
|
||||
|
||||
The outer variable is only used if there's no local one. So an occasional modification may happen if we forget `let`.
|
||||
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:
|
||||
|
||||
|
@ -128,7 +132,7 @@ Variables declared outside of any function, such as the outer `userName` in the
|
|||
|
||||
Global variables are visible from any function (unless shadowed by locals).
|
||||
|
||||
Usually, a function declares all variables specific to its task. Global variables only store project-level data, so when it's important that these variables are accesible from anywhere. Modern code has few or no globals. Most variables reside in their functions.
|
||||
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
|
||||
|
@ -204,6 +208,11 @@ function showMessage(from, text = anotherFunction()) {
|
|||
}
|
||||
```
|
||||
|
||||
```smart header="Evaluation of default parameters"
|
||||
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.
|
||||
|
||||
In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter.
|
||||
```
|
||||
|
||||
````smart header="Default parameters old-style"
|
||||
Old editions of JavaScript did not support default parameters. So there are alternative ways to support them, that you can find mostly in the old scripts.
|
||||
|
@ -257,13 +266,13 @@ There may be many occurrences of `return` in a single function. For instance:
|
|||
|
||||
```js run
|
||||
function checkAge(age) {
|
||||
if (age > 18) {
|
||||
if (age >= 18) {
|
||||
*!*
|
||||
return true;
|
||||
*/!*
|
||||
} else {
|
||||
*!*
|
||||
return confirm('Got a permission from the parents?');
|
||||
return confirm('Do you have permission from your parents?');
|
||||
*/!*
|
||||
}
|
||||
}
|
||||
|
@ -329,12 +338,24 @@ That doesn't work, because JavaScript assumes a semicolon after `return`. That'l
|
|||
return*!*;*/!*
|
||||
(some + long + expression + or + whatever * f(a) + f(b))
|
||||
```
|
||||
So, it effectively becomes an empty return. We should put the value on the same line instead.
|
||||
|
||||
So, it effectively becomes an empty return.
|
||||
|
||||
If we want the returned expression to wrap across multiple lines, we should start it at the same line as `return`. Or at least put the opening parentheses there as follows:
|
||||
|
||||
```js
|
||||
return (
|
||||
some + long + expression
|
||||
+ or +
|
||||
whatever * f(a) + f(b)
|
||||
)
|
||||
```
|
||||
And it will work just as we expect it to.
|
||||
````
|
||||
|
||||
## Naming a function [#function-naming]
|
||||
|
||||
Functions are actions. So their name is usually a verb. It should briefly, but as accurately as possible describe what the function does. So that a person who reads the code gets the right clue.
|
||||
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.
|
||||
|
||||
|
@ -368,17 +389,17 @@ 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 displays the `access granted/denied` message (should only perform the check and return the result).
|
||||
- `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. What they mean for you is determined by you and your team. Maybe it's pretty normal for your code to behave differently. But 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.
|
||||
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](http://jquery.com) framework defines a function `$`. The [LoDash](http://lodash.com/) library has its core function named `_`.
|
||||
For example, the [jQuery](http://jquery.com) framework defines a function with `$`. The [Lodash](http://lodash.com/) library has its core function named `_`.
|
||||
|
||||
These are exceptions. Generally functions names should be concise, but descriptive.
|
||||
These are exceptions. Generally functions names should be concise and descriptive.
|
||||
```
|
||||
|
||||
## Functions == Comments
|
||||
|
|
Before Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 48 KiB |
|
@ -1,4 +1,4 @@
|
|||
# Function expressions and arrows
|
||||
# Function expressions
|
||||
|
||||
In JavaScript, a function is not a "magical language structure", but a special kind of value.
|
||||
|
||||
|
@ -22,7 +22,6 @@ let sayHi = function() {
|
|||
|
||||
Here, the function is created and assigned to the variable explicitly, like any other value. No matter how the function is defined, it's just a value stored in the variable `sayHi`.
|
||||
|
||||
|
||||
The meaning of these code samples is the same: "create a function and put it into the variable `sayHi`".
|
||||
|
||||
We can even print out that value using `alert`:
|
||||
|
@ -41,7 +40,7 @@ Please note that the last line does not run the function, because there are no p
|
|||
|
||||
In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.
|
||||
|
||||
It is a special value of course, in the sense that we can call it like `sayHi()`.
|
||||
Surely, a function is a special 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.
|
||||
|
||||
|
@ -61,25 +60,25 @@ sayHi(); // Hello // this still works too (why wouldn't it)
|
|||
Here's what happens above in detail:
|
||||
|
||||
1. The Function Declaration `(1)` creates the function and puts it into the variable named `sayHi`.
|
||||
2. Line `(2)` copies it into the variable `func`.
|
||||
|
||||
Please note again: there are no parentheses after `sayHi`. If there were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself.
|
||||
2. Line `(2)` copies it into the variable `func`. Please note again: there are no parentheses after `sayHi`. If there were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself.
|
||||
3. Now the function can be called as both `sayHi()` and `func()`.
|
||||
|
||||
Note that we could also have used a Function Expression to declare `sayHi`, in the first line:
|
||||
|
||||
```js
|
||||
let sayHi = function() { ... };
|
||||
let sayHi = function() {
|
||||
alert( "Hello" );
|
||||
};
|
||||
|
||||
let func = sayHi;
|
||||
// ...
|
||||
```
|
||||
|
||||
Everything would work the same. Even more obvious what's going on, right?
|
||||
Everything would work the same.
|
||||
|
||||
|
||||
````smart header="Why there's a semicolon at the end?"
|
||||
There might be a question, why does Function Expression have a semicolon `;` at the end, and Function Declaration does not:
|
||||
````smart header="Why is there a semicolon at the end?"
|
||||
You might wonder, why does Function Expression have a semicolon `;` at the end, but Function Declaration does not:
|
||||
|
||||
```js
|
||||
function sayHi() {
|
||||
|
@ -93,7 +92,7 @@ let sayHi = function() {
|
|||
|
||||
The answer is simple:
|
||||
- There's no need for `;` at the end of code blocks and syntax structures that use them like `if { ... }`, `for { }`, `function f { }` etc.
|
||||
- A Function Expression is used inside the statement: `let sayHi = ...;`, as a value. It's not a code block. The semicolon `;` is recommended at the end of statements, no matter what is the value. So the semicolon here is not related to the Function Expression itself in any way, it just terminates the statement.
|
||||
- A Function Expression is used inside the statement: `let sayHi = ...;`, as a value. It's not a code block, but rather an assignment. The semicolon `;` is recommended at the end of statements, no matter what the value is. So the semicolon here is not related to the Function Expression itself, it just terminates the statement.
|
||||
````
|
||||
|
||||
## Callback functions
|
||||
|
@ -133,11 +132,11 @@ function showCancel() {
|
|||
ask("Do you agree?", showOk, showCancel);
|
||||
```
|
||||
|
||||
Before we explore how we can write it in a much shorter way, let's note that in the browser (and on the server-side in some cases) such functions are quite popular. The major difference between a real-life implementation and the example above is that real-life functions use more complex ways to interact with the user than a simple `confirm`. In the browser, such a function usually draws a nice-looking question window. But that's another story.
|
||||
In practice, such functions are quite useful. The major difference between a real-life `ask` and the example above is that real-life functions use more complex ways to interact with the user than a simple `confirm`. In the browser, such function usually draws a nice-looking question window. But that's another story.
|
||||
|
||||
**The arguments of `ask` are called *callback functions* or just *callbacks*.**
|
||||
**The arguments `showOk` and `showCancel` of `ask` are called *callback functions* or just *callbacks*.**
|
||||
|
||||
The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, `showOk` becomes the callback for the "yes" answer, and `showCancel` for the "no" answer.
|
||||
The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, `showOk` becomes the callback for "yes" answer, and `showCancel` for "no" answer.
|
||||
|
||||
We can use Function Expressions to write the same function much shorter:
|
||||
|
||||
|
@ -156,12 +155,10 @@ ask(
|
|||
*/!*
|
||||
```
|
||||
|
||||
|
||||
Here, functions are declared right inside the `ask(...)` call. They have no name, and so are called *anonymous*. Such functions are not accessible outside of `ask` (because they are not assigned to variables), but that's just what we want here.
|
||||
|
||||
Such code appears in our scripts very naturally, it's in the spirit of JavaScript.
|
||||
|
||||
|
||||
```smart header="A function is a value representing an \"action\""
|
||||
Regular values like strings or numbers represent the *data*.
|
||||
|
||||
|
@ -175,7 +172,7 @@ We can pass it between variables and run when we want.
|
|||
|
||||
Let's formulate the key differences between Function Declarations and Expressions.
|
||||
|
||||
First, the syntax: how to see what is what in the code.
|
||||
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.
|
||||
|
||||
|
@ -186,7 +183,7 @@ First, the syntax: how to see what is what in the code.
|
|||
}
|
||||
```
|
||||
- *Function Expression:* a function, created inside an expression or inside another syntax construct. Here, the function is created at the right side of the "assignment expression" `=`:
|
||||
|
||||
|
||||
```js
|
||||
// Function Expression
|
||||
let sum = function(a, b) {
|
||||
|
@ -196,19 +193,19 @@ First, the syntax: how to see what is what in the code.
|
|||
|
||||
The more subtle difference is *when* a function is created by the JavaScript engine.
|
||||
|
||||
**A Function Expression is created when the execution reaches it and is usable from then on.**
|
||||
**A Function Expression is created when the execution reaches it and is usable only from that moment.**
|
||||
|
||||
Once the execution flow passes to the right side of the assignment `let sum = function…` -- here we go, the function is created and can be used (assigned, called etc) from now on.
|
||||
Once the execution flow passes to the right side of the assignment `let sum = function…` -- here we go, the function is created and can be used (assigned, called, etc. ) from now on.
|
||||
|
||||
Function Declarations are different.
|
||||
|
||||
**A Function Declaration is usable in the whole script/code block.**
|
||||
**A Function Declaration can be called earlier than it is defined.**
|
||||
|
||||
In other words, when JavaScript *prepares* to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage".
|
||||
For example, a global Function Declaration is visible in the whole script, no matter where it is.
|
||||
|
||||
And after all of the Function Declarations are processed, the execution goes on.
|
||||
That's due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an "initialization stage".
|
||||
|
||||
As a result, a function declared as a Function Declaration can be called earlier than it is defined.
|
||||
And after all Function Declarations are processed, the code is executed. So it has access to these functions.
|
||||
|
||||
For example, this works:
|
||||
|
||||
|
@ -224,7 +221,7 @@ function sayHi(name) {
|
|||
|
||||
The Function Declaration `sayHi` is created when JavaScript is preparing to start the script and is visible everywhere in it.
|
||||
|
||||
...If it was a Function Expression, then it wouldn't work:
|
||||
...If it were a Function Expression, then it wouldn't work:
|
||||
|
||||
```js run refresh untrusted
|
||||
*!*
|
||||
|
@ -238,13 +235,13 @@ let sayHi = function(name) { // (*) no magic any more
|
|||
|
||||
Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late.
|
||||
|
||||
**When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.**
|
||||
Another special feature of Function Declarations is their block scope.
|
||||
|
||||
Sometimes that's handy to declare a local function only needed in that block alone. But that feature may also cause problems.
|
||||
**In strict mode, when a Function Declaration is within a code block, it's visible everywhere inside that block. But not outside of it.**
|
||||
|
||||
For instance, let's imagine that we need to declare a function `welcome()` depending on the `age` variable that we get during runtime. And then we plan to use it some time later.
|
||||
|
||||
The code below doesn't work:
|
||||
If we use Function Declaration, it won't work as intended:
|
||||
|
||||
```js run
|
||||
let age = prompt("What is your age?", 18);
|
||||
|
@ -292,7 +289,7 @@ if (age < 18) {
|
|||
|
||||
} else {
|
||||
|
||||
function welcome() { // for age = 16, this "welcome" is never created
|
||||
function welcome() {
|
||||
alert("Greetings!");
|
||||
}
|
||||
}
|
||||
|
@ -309,7 +306,7 @@ What can we do to make `welcome` visible outside of `if`?
|
|||
|
||||
The correct approach would be to use a Function Expression and assign `welcome` to the variable that is declared outside of `if` and has the proper visibility.
|
||||
|
||||
Now it works as intended:
|
||||
This code works as intended:
|
||||
|
||||
```js run
|
||||
let age = prompt("What is your age?", 18);
|
||||
|
@ -351,112 +348,11 @@ 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 to consider is Function Declaration syntax, the one we used before. It gives more freedom in how to organize our code, because we can call such functions before they are declared.
|
||||
As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.
|
||||
|
||||
It's also a little bit easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching".
|
||||
That's also better for readability, as it's easier to look up `function f(…) {…}` in the code than `let f = function(…) {…};`. Function Declarations are more "eye-catching".
|
||||
|
||||
...But if a Function Declaration does not suit us for some reason (we've seen an example above), then Function Expression should be used.
|
||||
```
|
||||
|
||||
|
||||
## Arrow functions [#arrow-functions]
|
||||
|
||||
There's one more 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 has arguments `arg1..argN`, evaluates the `expression` on the right side with their use and returns its result.
|
||||
|
||||
In other words, it's roughly the same as:
|
||||
|
||||
```js
|
||||
let func = function(arg1, arg2, ...argN) {
|
||||
return expression;
|
||||
}
|
||||
```
|
||||
|
||||
...But much more concise.
|
||||
|
||||
Let's see an example:
|
||||
|
||||
```js run
|
||||
let sum = (a, b) => a + b;
|
||||
|
||||
/* The arrow function is a shorter form of:
|
||||
|
||||
let sum = function(a, b) {
|
||||
return a + b;
|
||||
};
|
||||
*/
|
||||
|
||||
alert( sum(1, 2) ); // 3
|
||||
|
||||
```
|
||||
|
||||
If we have only one argument, then parentheses can be omitted, making that even shorter:
|
||||
|
||||
```js run
|
||||
// same as
|
||||
// let double = function(n) { return n * 2 }
|
||||
*!*
|
||||
let double = n => n * 2;
|
||||
*/!*
|
||||
|
||||
alert( double(3) ); // 6
|
||||
```
|
||||
|
||||
If there are no arguments, parentheses should be empty (but they should be present):
|
||||
|
||||
```js run
|
||||
let sayHi = () => alert("Hello!");
|
||||
|
||||
sayHi();
|
||||
```
|
||||
|
||||
Arrow functions can be used in the same way as Function Expressions.
|
||||
|
||||
For instance, here's the rewritten example with `welcome()`:
|
||||
|
||||
```js run
|
||||
let age = prompt("What is your age?", 18);
|
||||
|
||||
let welcome = (age < 18) ?
|
||||
() => alert('Hello') :
|
||||
() => alert("Greetings!");
|
||||
|
||||
welcome(); // ok now
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```smart header="Multiline arrow functions"
|
||||
|
||||
The examples above took arguments from the left of `=>` and evaluated the right-side expression with them.
|
||||
|
||||
Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal `return` within them.
|
||||
|
||||
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, use return to get results
|
||||
*/!*
|
||||
};
|
||||
|
||||
alert( sum(1, 2) ); // 3
|
||||
```
|
||||
|
||||
```smart header="More to come"
|
||||
Here we praised arrow functions for brevity. But that's not all! Arrow functions have other interesting features. We'll return to them later in the chapter <info:arrow-functions>.
|
||||
|
||||
For now, we can already use them for one-line actions and callbacks.
|
||||
...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
|
||||
|
@ -467,12 +363,6 @@ For now, we can already use them for one-line actions and callbacks.
|
|||
- Function Declarations are processed before the code block is executed. They are visible everywhere in the block.
|
||||
- Function Expressions are created when the execution flow reaches them.
|
||||
|
||||
|
||||
In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable.
|
||||
|
||||
So we should use a Function Expression only when a Function Declaration is not fit for the task. We've seen a couple of examples of that in this chapter, and will see more in the future.
|
||||
|
||||
Arrow functions are handy 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.
|
||||
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.
|
|
@ -1,7 +1,7 @@
|
|||
|
||||
# Rewrite with arrow functions
|
||||
|
||||
Replace Function Expressions with arrow functions in the code:
|
||||
Replace Function Expressions with arrow functions in the code below:
|
||||
|
||||
```js run
|
||||
function ask(question, yes, no) {
|
111
1-js/02-first-steps/16-arrow-functions-basics/article.md
Normal file
|
@ -0,0 +1,111 @@
|
|||
# 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:
|
||||
|
||||
```js run
|
||||
let sum = (a, b) => a + b;
|
||||
|
||||
/* This arrow function is a shorter form of:
|
||||
|
||||
let sum = function(a, b) {
|
||||
return a + b;
|
||||
};
|
||||
*/
|
||||
|
||||
alert( sum(1, 2) ); // 3
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```js run
|
||||
*!*
|
||||
let double = n => n * 2;
|
||||
// roughly the same as: let double = function(n) { return n * 2 }
|
||||
*/!*
|
||||
|
||||
alert( double(3) ); // 6
|
||||
```
|
||||
|
||||
- If there are no arguments, parentheses will be empty (but they should be present):
|
||||
|
||||
```js run
|
||||
let sayHi = () => alert("Hello!");
|
||||
|
||||
sayHi();
|
||||
```
|
||||
|
||||
Arrow functions can be used in the same way as Function Expressions.
|
||||
|
||||
For instance, to dynamically create a function:
|
||||
|
||||
```js run
|
||||
let age = prompt("What is your age?", 18);
|
||||
|
||||
let welcome = (age < 18) ?
|
||||
() => alert('Hello') :
|
||||
() => alert("Greetings!");
|
||||
|
||||
welcome(); // ok now
|
||||
```
|
||||
|
||||
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 examples above took arguments from the left of `=>` and evaluated the right-side expression with them.
|
||||
|
||||
Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal `return` within them.
|
||||
|
||||
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"
|
||||
*/!*
|
||||
};
|
||||
|
||||
alert( sum(1, 2) ); // 3
|
||||
```
|
||||
|
||||
```smart header="More to come"
|
||||
Here we praised arrow functions for brevity. But that's not all!
|
||||
|
||||
Arrow functions have other interesting features.
|
||||
|
||||
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 <info:arrow-functions>.
|
||||
|
||||
For now, we can already use arrow functions for one-line actions and callbacks.
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
Arrow functions are handy 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.
|
||||
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.
|
|
@ -53,7 +53,7 @@ To fully enable all features of modern JavaScript, we should start scripts with
|
|||
...
|
||||
```
|
||||
|
||||
The directive must be at the top of a script or at the beginning of a function.
|
||||
The directive must be at the top of a script or at the beginning of a function body.
|
||||
|
||||
Without `"use strict"`, everything still works, but some features behave in the old-fashion, "compatible" way. We'd generally prefer the modern behavior.
|
||||
|
||||
|
@ -102,8 +102,8 @@ More in: <info:variables> and <info:types>.
|
|||
|
||||
We're using a browser as a working environment, so basic UI functions will be:
|
||||
|
||||
[`prompt(question[, default])`](mdn:api/Window/prompt)
|
||||
: Ask a `question`, and return either what the visitor entered or `null` if they pressed "cancel".
|
||||
[`prompt(question, [default])`](mdn:api/Window/prompt)
|
||||
: Ask a `question`, and return either what the visitor entered or `null` if they clicked "cancel".
|
||||
|
||||
[`confirm(question)`](mdn:api/Window/confirm)
|
||||
: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`.
|
||||
|
@ -143,13 +143,13 @@ Assignments
|
|||
: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
|
||||
|
||||
Bitwise
|
||||
: Bitwise operators work with integers on bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
|
||||
: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
|
||||
|
||||
Ternary
|
||||
Conditional
|
||||
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
|
||||
|
||||
Logical operators
|
||||
: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped.
|
||||
: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped (not necessary `true`/`false`). Logical NOT `!` converts the operand to boolean type and returns the inverse value.
|
||||
|
||||
Comparisons
|
||||
: Equality check `==` for values of different types converts them to a number (except `null` and `undefined` that equal each other and nothing else), so these are equal:
|
||||
|
@ -161,13 +161,13 @@ Comparisons
|
|||
|
||||
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, so:
|
||||
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.
|
||||
|
||||
Logical operators
|
||||
Other operators
|
||||
: There are few others, like a comma operator.
|
||||
|
||||
More in: <info:operators>, <info:comparison>, <info:logical-operators>.
|
||||
|
@ -245,11 +245,9 @@ We covered three ways to create a function in JavaScript:
|
|||
let result = a + b;
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function.
|
||||
|
||||
3. Arrow functions:
|
||||
|
||||
```js
|
||||
|
@ -274,13 +272,7 @@ We covered three ways to create a function in JavaScript:
|
|||
- Parameters can have default values: `function sum(a = 1, b = 2) {...}`.
|
||||
- Functions always return something. If there's no `return` statement, then the result is `undefined`.
|
||||
|
||||
|
||||
| Function Declaration | Function Expression |
|
||||
|----------------------|---------------------|
|
||||
| visible in the whole code block | created when the execution reaches it |
|
||||
| - | can have a name, visible only inside the function |
|
||||
|
||||
More: see <info:function-basics>, <info:function-expressions-arrows>.
|
||||
Details: see <info:function-basics>, <info:arrow-functions-basics>.
|
||||
|
||||
## More to come
|
||||
|
|
@ -2,45 +2,45 @@
|
|||
|
||||
Before writing more complex code, let's talk about debugging.
|
||||
|
||||
All modern browsers and most other environments support "debugging" -- a special UI in developer tools that makes finding and fixing errors much easier.
|
||||
[Debugging](https://en.wikipedia.org/wiki/Debugging) is the process of finding and fixing errors within a script. All modern browsers and most other environments support debugging tools -- a special UI in developer tools that makes debugging much easier. It also allows to trace the code step by step to see what exactly is going on.
|
||||
|
||||
We'll be using Chrome here, because it's probably the most feature-rich in this aspect.
|
||||
We'll be using Chrome here, because it has enough features, most other browsers have a similar process.
|
||||
|
||||
## The "sources" pane
|
||||
## The "Sources" panel
|
||||
|
||||
Your Chrome version may look a little bit different, but it still should be obvious what's there.
|
||||
|
||||
- Open the [example page](debugging/index.html) in Chrome.
|
||||
- Turn on developer tools with `key:F12` (Mac: `key:Cmd+Opt+I`).
|
||||
- Select the `sources` pane.
|
||||
- Select the `Sources` panel.
|
||||
|
||||
Here's what you should see if you are doing it for the first time:
|
||||
|
||||

|
||||

|
||||
|
||||
The toggler button <span class="devtools" style="background-position:-168px -76px"></span> opens the tab with files.
|
||||
The toggler button <span class="devtools" style="background-position:-172px -98px"></span> opens the tab with files.
|
||||
|
||||
Let's click it and select `index.html` and then `hello.js` in the tree view. Here's what should show up:
|
||||
Let's click it and select `hello.js` in the tree view. Here's what should show up:
|
||||
|
||||

|
||||

|
||||
|
||||
Here we can see three zones:
|
||||
The Sources panel has 3 parts:
|
||||
|
||||
1. The **Resources zone** lists HTML, JavaScript, CSS and other files, including images that are attached to the page. Chrome extensions may appear here too.
|
||||
2. The **Source zone** shows the source code.
|
||||
3. The **Information and control zone** is for debugging, we'll explore it soon.
|
||||
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 <span class="devtools" style="background-position:-200px -76px"></span> again to hide the resources list and give the code some space.
|
||||
Now you could click the same toggler <span class="devtools" style="background-position:-172px -122px"></span> again to hide the resources list and give the code some space.
|
||||
|
||||
## Console
|
||||
|
||||
If we press `Esc`, then a console opens below. We can type commands there and press `key:Enter` to execute.
|
||||
If we press `key:Esc`, then a console opens below. We can type commands there and press `key:Enter` to execute.
|
||||
|
||||
After a statement is executed, its result is shown below.
|
||||
|
||||
For example, here `1+2` results in `3`, and `hello("debugger")` returns nothing, so the result is `undefined`:
|
||||
|
||||

|
||||

|
||||
|
||||
## Breakpoints
|
||||
|
||||
|
@ -50,14 +50,14 @@ Congratulations! You've set a breakpoint. Please also click on the number for li
|
|||
|
||||
It should look like this (blue is where you should click):
|
||||
|
||||

|
||||

|
||||
|
||||
A *breakpoint* is a point of code where the debugger will automatically pause the JavaScript execution.
|
||||
|
||||
While the code is paused, we can examine current variables, execute commands in the console etc. In other words, we can debug it.
|
||||
|
||||
We can always find a list of breakpoints in the right pane. That's useful when we have many breakpoints in various files. It allows to:
|
||||
- Quickly jump to the breakpoint in the code (by clicking on it in the right pane).
|
||||
We can always find a list of breakpoints in the right panel. That's useful when we have many breakpoints in various files. It allows us to:
|
||||
- Quickly jump to the breakpoint in the code (by clicking on it in the right panel).
|
||||
- Temporarily disable the breakpoint by unchecking it.
|
||||
- Remove the breakpoint by right-clicking and selecting Remove.
|
||||
- ...And so on.
|
||||
|
@ -70,7 +70,7 @@ That's handy when we need to stop only for a certain variable value or for certa
|
|||
|
||||
## Debugger command
|
||||
|
||||
We can also pause the code by using the `debugger` command, like this:
|
||||
We can also pause the code by using the `debugger` command in it, like this:
|
||||
|
||||
```js
|
||||
function hello(name) {
|
||||
|
@ -89,11 +89,11 @@ That's very convenient when we are in a code editor and don't want to switch to
|
|||
|
||||
## Pause and look around
|
||||
|
||||
In our example, `hello()` is called during the page load, so the easiest way to activate the debugger is to reload the page. So let's press `key:F5` (Windows, Linux) or `key:Cmd+R` (Mac).
|
||||
In our example, `hello()` is called during the page load, so the easiest way to activate the debugger (after we've set the breakpoints) is to reload the page. So let's press `key:F5` (Windows, Linux) or `key:Cmd+R` (Mac).
|
||||
|
||||
As the breakpoint is set, the execution pauses at the 4th line:
|
||||
|
||||

|
||||

|
||||
|
||||
Please open the informational dropdowns to the right (labeled with arrows). They allow you to examine the current code state:
|
||||
|
||||
|
@ -105,7 +105,7 @@ Please open the informational dropdowns to the right (labeled with arrows). They
|
|||
|
||||
At the current moment the debugger is inside `hello()` call, called by a script in `index.html` (no function there, so it's called "anonymous").
|
||||
|
||||
If you click on a stack item, the debugger jumps to the corresponding code, and all its variables can be examined as well.
|
||||
If you click on a stack item (e.g. "anonymous"), the debugger jumps to the corresponding code, and all its variables can be examined as well.
|
||||
3. **`Scope` -- current variables.**
|
||||
|
||||
`Local` shows local function variables. You can also see their values highlighted right over the source.
|
||||
|
@ -118,52 +118,65 @@ Please open the informational dropdowns to the right (labeled with arrows). They
|
|||
|
||||
Now it's time to *trace* the script.
|
||||
|
||||
There are buttons for it at the top of the right pane. Let's engage them.
|
||||
|
||||
<span class="devtools" style="background-position:-7px -76px"></span> -- continue the execution, hotkey `key:F8`.
|
||||
There are buttons for it at the top of the right panel. Let's engage them.
|
||||
<!-- https://github.com/ChromeDevTools/devtools-frontend/blob/master/front_end/Images/src/largeIcons.svg -->
|
||||
<span class="devtools" style="background-position:-146px -168px"></span> -- "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.
|
||||
|
||||
Here's what we can see after a click on it:
|
||||
|
||||

|
||||

|
||||
|
||||
The execution has resumed, reached another breakpoint inside `say()` and paused there. Take a look at the "Call stack" at the right. It has increased by one more call. We're inside `say()` now.
|
||||
The execution has resumed, reached another breakpoint inside `say()` and paused there. Take a look at the "Call Stack" at the right. It has increased by one more call. We're inside `say()` now.
|
||||
|
||||
<span class="devtools" style="background-position:-137px -76px"></span> -- make a step (run the next command), but *don't go into the function*, hotkey `key:F10`.
|
||||
: If we click it now, `alert` will be shown. The important thing is that `alert` can be any function, the execution "steps over it", skipping the function internals.
|
||||
<span class="devtools" style="background-position:-200px -190px"></span> -- "Step": run the next command, hotkey `key:F9`.
|
||||
: Run the next statement. If we click it now, `alert` will be shown.
|
||||
|
||||
<span class="devtools" style="background-position:-72px -76px"></span> -- make a step, hotkey `key:F11`.
|
||||
: The same as the previous one, but "steps into" nested functions. Clicking this will step through all script actions one by one.
|
||||
Clicking this again and again will step through all script statements one by one.
|
||||
|
||||
<span class="devtools" style="background-position:-104px -76px"></span> -- continue the execution till the end of the current function, hotkey `key:Shift+F11`.
|
||||
: The execution would stop at the very last line of the current function. That's handy when we accidentally entered a nested call using <span class="devtools" style="background-position:-72px -76px"></span>, but it does not interest us, and we want to continue to its end as soon as possible.
|
||||
<span class="devtools" style="background-position:-62px -192px"></span> -- "Step over": run the next command, but *don't go into a function*, hotkey `key:F10`.
|
||||
: Similar to the previous the "Step" command, but behaves differently if the next statement is a function call. That is: not a built-in, like `alert`, but a function of our own.
|
||||
|
||||
<span class="devtools" style="background-position:-7px -28px"></span> -- enable/disable all breakpoints.
|
||||
The "Step" command goes into it and pauses the execution at its first line, while "Step over" executes the nested function call invisibly, skipping the function internals.
|
||||
|
||||
The execution is then paused immediately after that function.
|
||||
|
||||
That's good if we're not interested to see what happens inside the function call.
|
||||
|
||||
<span class="devtools" style="background-position:-4px -194px"></span> -- "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.
|
||||
|
||||
<span class="devtools" style="background-position:-32px -194px"></span> -- "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 <span class="devtools" style="background-position:-200px -190px"></span>, but it does not interest us, and we want to continue to its end as soon as possible.
|
||||
|
||||
<span class="devtools" style="background-position:-61px -74px"></span> -- enable/disable all breakpoints.
|
||||
: That button does not move the execution. Just a mass on/off for breakpoints.
|
||||
|
||||
<span class="devtools" style="background-position:-264px -4px"></span> -- enable/disable automatic pause in case of an error.
|
||||
<span class="devtools" style="background-position:-90px -146px"></span> -- enable/disable automatic pause in case of an error.
|
||||
: When enabled, and the developer tools is open, a script error automatically pauses the execution. Then we can analyze variables 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.
|
||||
|
||||
```smart header="Continue to here"
|
||||
Right click on a line of code opens the context menu with a great option called "Continue to here".
|
||||
|
||||
That's handy when we want to move multiple steps forward, but we're too lazy to set a breakpoint.
|
||||
That's handy when we want to move multiple steps forward to the line, but we're too lazy to set a breakpoint.
|
||||
```
|
||||
|
||||
## Logging
|
||||
|
||||
To output something to console, there's `console.log` function.
|
||||
To output something to console from our code, there's `console.log` function.
|
||||
|
||||
For instance, this outputs values from `0` to `4` to console:
|
||||
|
||||
```js run
|
||||
// open console to see
|
||||
for (let i = 0; i < 5; i++) {
|
||||
console.log("value", i);
|
||||
console.log("value,", i);
|
||||
}
|
||||
```
|
||||
|
||||
Regular users don't see that output, it is in the console. To see it, either open the Console tab of developer tools or press `key:Esc` while in another tab: that opens the console at the bottom.
|
||||
Regular users don't see that output, it is in the console. To see it, either open the Console panel of developer tools or press `key:Esc` while in another panel: that opens the console at the bottom.
|
||||
|
||||
If we have enough logging in our code, then we can see what's going on from the records, without the debugger.
|
||||
|
||||
|
@ -172,12 +185,12 @@ If we have enough logging in our code, then we can see what's going on from the
|
|||
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 <span class="devtools" style="background-position:-264px -4px"></span> is "on")
|
||||
3. An error (if dev tools are open and the button <span class="devtools" style="background-position:-90px -146px"></span> is "on").
|
||||
|
||||
Then we can examine variables and step on to see where the execution goes wrong.
|
||||
When paused, we can debug - examine variables and trace the code to see where the execution goes wrong.
|
||||
|
||||
There are many more options in developer tools than covered here. The full manual is at <https://developers.google.com/web/tools/chrome-devtools>.
|
||||
|
||||
The information from this chapter is enough to begin debugging, but later, especially if you do a lot of browser stuff, please go there and look through more advanced capabilities of developer tools.
|
||||
|
||||
Oh, and also you can click at various places of dev tools and just see what's showing up. That's probably the fastest route to learn dev tools. Don't forget about the right click as well!
|
||||
Oh, and also you can click at various places of dev tools and just see what's showing up. That's probably the fastest route to learn dev tools. Don't forget about the right click and context menus!
|
||||
|
|
Before Width: | Height: | Size: 61 KiB |
After Width: | Height: | Size: 120 KiB |
Before Width: | Height: | Size: 98 KiB |
Before Width: | Height: | Size: 60 KiB |
After Width: | Height: | Size: 140 KiB |
Before Width: | Height: | Size: 116 KiB |
Before Width: | Height: | Size: 31 KiB |
After Width: | Height: | Size: 42 KiB |
Before Width: | Height: | Size: 60 KiB |
Before Width: | Height: | Size: 80 KiB |
After Width: | Height: | Size: 172 KiB |
Before Width: | Height: | Size: 149 KiB |
Before Width: | Height: | Size: 64 KiB |
After Width: | Height: | Size: 166 KiB |
Before Width: | Height: | Size: 112 KiB |
Before Width: | Height: | Size: 72 KiB |
1
1-js/03-code-quality/01-debugging-chrome/chrome-tabs.svg
Normal file
After Width: | Height: | Size: 162 KiB |
Before Width: | Height: | Size: 134 KiB |
Before Width: | Height: | Size: 26 KiB |
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 41 KiB |