Skip to content

Sync with upstream @ a6fdfda0 #113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3,026 commits into from
Closed
Changes from all commits
Commits
Show all changes
3026 commits
Select commit Hold shift + click to select a range
581117f
Merge pull request #2621 from leviding/patch-36
iliakan Jun 13, 2021
dcf4b5b
closes #2619
iliakan Jun 13, 2021
2290bd6
Merge pull request #2616 from joaquinelio/patch-8
iliakan Jun 13, 2021
bcb47b7
Merge pull request #2612 from joaquinelio/patch-4
iliakan Jun 13, 2021
5f927bd
Merge pull request #2611 from AhmedElaguab/master
iliakan Jun 13, 2021
4d46f12
Merge pull request #2606 from Dorin-David/patch-1
iliakan Jun 13, 2021
e4ac603
Merge pull request #2605 from web-padawan/patch-1
iliakan Jun 13, 2021
ee5853d
Merge pull request #2604 from odsantos/regex-methods
iliakan Jun 13, 2021
bcf2e48
minor fixes
iliakan Jun 13, 2021
225a36f
Merge branch 'master' of github.com:javascript-tutorial/en.javascript…
iliakan Jun 13, 2021
617dfc7
minor fixes
iliakan Jun 13, 2021
3d88d33
Update article.md
ZYinMD Jun 13, 2021
e2d1823
minor fixes
iliakan Jun 13, 2021
614e29e
minor fixes
iliakan Jun 13, 2021
a171b0a
fix typo in 1-js/05-data-types/03-string
ZYinMD Jun 13, 2021
e527c61
Merge pull request #2630 from ZYinMD/patch-10
iliakan Jun 13, 2021
b258e8f
minor fixes
iliakan Jun 14, 2021
fb4fc33
minor fixes
iliakan Jun 15, 2021
2dce19e
"inserts into" instead of "appends to"
joaquinelio Jun 16, 2021
497ca99
Update article.md
joaquinelio Jun 16, 2021
9680c67
Merge pull request #2633 from joaquinelio/patch-4
iliakan Jun 16, 2021
cd466c5
Unnecessary escape characters in cookie.js
NNboru Jun 17, 2021
8c910b4
Update article.md
joaquinelio Jun 18, 2021
8cf2d51
Update article.md
joaquinelio Jun 18, 2021
0c41930
Update article.md
joaquinelio Jun 18, 2021
263f57e
Update article.md
joaquinelio Jun 18, 2021
492f506
Merge pull request #2555 from joaquinelio/patch-6
iliakan Jun 18, 2021
a6dfbb7
minor fixes
iliakan Jun 18, 2021
29f0121
Merge pull request #2636 from NNboru/patch-1
iliakan Jun 18, 2021
de36d0d
update one code comment in 1-js/09-classes/04-private-protected-prope…
ZYinMD Jun 18, 2021
c45e78f
Maybe. "accessors" link
joaquinelio Jun 18, 2021
d43bdd2
slightly improve clarity on Promise.all()
ZYinMD Jun 19, 2021
e49bc3b
Merge pull request #2627 from ZYinMD/patch-5
iliakan Jun 19, 2021
e877796
closes #2641
iliakan Jun 19, 2021
ff53f06
minor fixes
iliakan Jun 19, 2021
cf82cc3
minor fixes
iliakan Jun 19, 2021
85282ef
minor fixes
iliakan Jun 19, 2021
a40ca9a
minor fixes
iliakan Jun 19, 2021
54347b7
minor fixes
iliakan Jun 19, 2021
df6e5a4
minor fixes
iliakan Jun 19, 2021
e769408
minor fixes
iliakan Jun 19, 2021
de81cb4
minor fixes
iliakan Jun 19, 2021
7dacfd4
minor fixes
iliakan Jun 19, 2021
3661393
minor fixes
iliakan Jun 19, 2021
1b16f9d
Merge pull request #2640 from ZYinMD/patch-17
iliakan Jun 19, 2021
6f14c39
Merge pull request #2639 from joaquinelio/patch-4
iliakan Jun 19, 2021
52eaa63
typo
joaquinelio Jun 20, 2021
9847492
Typo in Ch 15 Functions
Yoona8 Jun 20, 2021
140c75d
Merge pull request #2644 from Yoona8/master
iliakan Jun 20, 2021
ffe91a6
Merge pull request #2643 from joaquinelio/patch-6
iliakan Jun 20, 2021
8558fa8
Merge pull request #2638 from ZYinMD/patch-16
iliakan Jun 20, 2021
b19a6f0
minor fixes
iliakan Jun 21, 2021
66bad3f
fix typo in 5-network/02-formdata
ZYinMD Jun 22, 2021
d7c2f08
Add one letter in 5-network/03-fetch-progress
ZYinMD Jun 22, 2021
c4efc35
minor grammar change in webcomponents-intro
ZYinMD Jun 23, 2021
b855f6c
add a section about css animation performance
ZYinMD Jun 24, 2021
9b99012
Merge pull request #2654 from ZYinMD/patch-24
iliakan Jun 24, 2021
c41361f
animation
iliakan Jun 24, 2021
8b3730b
minor fixes
iliakan Jun 24, 2021
2961588
minor fixes
iliakan Jun 24, 2021
753182b
minor fixes
iliakan Jun 24, 2021
7d838b3
minor fixes
iliakan Jun 24, 2021
32f01fb
minor fixes
iliakan Jun 24, 2021
6c15ba4
minor fixes
iliakan Jun 24, 2021
771aab4
minor fixes
iliakan Jun 24, 2021
2eb4251
minor fixes
iliakan Jun 24, 2021
2811211
minor fixes
iliakan Jun 24, 2021
27af482
minor fixes
iliakan Jun 24, 2021
934d32b
minor fixes
iliakan Jun 24, 2021
4420427
minor fixes
iliakan Jun 24, 2021
e609815
minor fixes
iliakan Jun 24, 2021
e06bc63
minor fixes
iliakan Jun 24, 2021
e79ce9d
minor fixes
iliakan Jun 25, 2021
c001068
minor fixes
iliakan Jun 25, 2021
dab34f7
minor fixes
iliakan Jun 26, 2021
e9d2a31
minor fixes
iliakan Jun 26, 2021
a0af69e
minor fixes
iliakan Jun 26, 2021
4ed51aa
minor fixes
iliakan Jun 26, 2021
54688eb
minor fixes
iliakan Jun 26, 2021
6dda47f
minor fixes
iliakan Jun 26, 2021
e8d7f37
minor fixes
iliakan Jun 26, 2021
9bba570
minor fixes
iliakan Jun 26, 2021
7725acc
minor fixes
iliakan Jun 26, 2021
bed62e1
Add generator.return
Manik2375 Jun 27, 2021
624b48b
Update article.md
Manik2375 Jun 27, 2021
8db6519
minor fixes
iliakan Jun 27, 2021
8752573
minor fixes
iliakan Jun 27, 2021
76656bd
minor fixes
iliakan Jun 27, 2021
16b9bda
minor fixes
iliakan Jun 28, 2021
2275894
Merge pull request #2657 from Manik2375/generator.return
iliakan Jul 1, 2021
e195256
Response header name is changed to the right one
websavva Jul 3, 2021
16de27d
Fix a small grammar mistake
iliyu Jul 4, 2021
89e22f8
confusing line
joaquinelio Jul 13, 2021
02c75d2
Update task.md
joaquinelio Jul 13, 2021
19ec58b
Update article.md
Gammadon Jul 16, 2021
ce38273
add a missing colon
mahdyar Jul 17, 2021
c3214e7
Update article.md
iliakan Jul 21, 2021
1bf6973
Merge pull request #2673 from mahdyar/patch-1
iliakan Jul 22, 2021
667eb56
Merge pull request #2672 from Gammadon/patch-1
iliakan Jul 22, 2021
a5f339e
Merge pull request #2670 from joaquinelio/patch-6
iliakan Jul 22, 2021
237d883
Merge pull request #2662 from riri-yu/patch-1
iliakan Jul 22, 2021
cb97b72
Merge pull request #2661 from WebSavva/patch-1
iliakan Jul 22, 2021
df215cd
Merge pull request #2653 from ZYinMD/patch-21
iliakan Jul 22, 2021
614c85a
minor fixes
iliakan Jul 22, 2021
0082fbe
minor fixes
iliakan Jul 22, 2021
173ce27
Merge pull request #2649 from ZYinMD/patch-20
iliakan Jul 22, 2021
823eea4
Merge pull request #2648 from ZYinMD/patch-19
iliakan Jul 22, 2021
2957e71
minor fixes
iliakan Jul 23, 2021
1b1a2c4
minor fixes
iliakan Jul 23, 2021
9c5388c
pointer events improvements
iliakan Jul 24, 2021
57ff060
minor fixes
iliakan Jul 24, 2021
2a6fd54
old and new
joaquinelio Jul 26, 2021
ef8d576
Merge pull request #2680 from joaquinelio/patch-4
iliakan Jul 26, 2021
05a97a0
Update article.md
RainbowDashy Aug 1, 2021
12d7968
Make use of `loadJson` inside `loadGithubUser`
Aug 6, 2021
1808fe3
slider not working on movile
joaquinelio Aug 8, 2021
4a7fe13
Update index.html
joaquinelio Aug 8, 2021
58f9c8d
minor fixes
iliakan Aug 8, 2021
bc08fd1
Merge pull request #2689 from joaquinelio/patch-8
iliakan Aug 8, 2021
6b4cfc2
Fix grammar
siimpragi Aug 9, 2021
d404087
Fix typo.
odsantos Aug 9, 2021
95ad576
Update article.md
msmilkshake Aug 11, 2021
f17c07a
Fix compound interest formula
shvchk Aug 14, 2021
a19e517
Update URLs
odsantos Aug 14, 2021
d3ae613
Merge pull request #2683 from RainbowDashy/patch-1
iliakan Aug 14, 2021
ed3b2c0
Merge pull request #2696 from odsantos/property-descriptors
iliakan Aug 14, 2021
71688e7
Merge pull request #2695 from shvchk/master
iliakan Aug 14, 2021
7edd7c3
Merge pull request #2694 from msmilkshake/patch-1
iliakan Aug 14, 2021
71f8a9e
Merge pull request #2693 from odsantos/css-animations-typo
iliakan Aug 14, 2021
3b7a35e
Merge pull request #2692 from siimpragi/patch-1
iliakan Aug 14, 2021
a6c0fad
Merge pull request #2686 from mindv0rtex/patch-1
iliakan Aug 14, 2021
4d01fc2
minor fixes
iliakan Aug 15, 2021
1b31575
promise chain flow
joaquinelio Aug 15, 2021
8287e24
edge
joaquinelio Aug 16, 2021
623737b
Update article.md
deisner Aug 21, 2021
22b7b51
Update article.md
Aug 26, 2021
e69a943
Update urls
imba-tjd Aug 27, 2021
08a5308
Update article.md
baooab Sep 11, 2021
1059096
Update URL.
odsantos Sep 14, 2021
df39e1a
Update article.md
vladdoroniuk Sep 14, 2021
76ef126
Fix typo
rizkyzhang Sep 22, 2021
7abc297
picture minor fixes
iliakan Sep 25, 2021
b09e38c
minor fixes
iliakan Sep 25, 2021
7651ae0
minor typo
fionatagious Oct 1, 2021
2f98054
chore: fix a typo
mahdyar Oct 4, 2021
f4801c3
closes #2738
iliakan Oct 10, 2021
171d2e7
Merge pull request #2731 from mahdyar/patch-1
iliakan Oct 10, 2021
3d47402
Merge pull request #2729 from fionatagious/patch-1
iliakan Oct 10, 2021
5c1ee32
Merge pull request #2725 from rizkyzhang/patch-6
iliakan Oct 10, 2021
1c63023
Merge pull request #2721 from xirly/master
iliakan Oct 10, 2021
9e4a1e9
Merge pull request #2720 from odsantos/object-references
iliakan Oct 10, 2021
8794b71
Merge pull request #2717 from baooab/patch-9
iliakan Oct 10, 2021
2e494c7
Merge pull request #2697 from joaquinelio/patch-4
iliakan Oct 10, 2021
f1210b4
minor
iliakan Oct 10, 2021
cbc4350
Merge pull request #2698 from joaquinelio/patch-5
iliakan Oct 10, 2021
0d67376
Merge pull request #2701 from deisner/patch-1
iliakan Oct 10, 2021
ab2c57c
Merge pull request #2704 from wilburn98/master
iliakan Oct 10, 2021
193319c
Merge pull request #2705 from imba-tjd/patch-1
iliakan Oct 10, 2021
e3b10e6
sort-by-field fix
joneskj55 Oct 10, 2021
91a89ea
Update article.md
LexaWin Oct 11, 2021
eda333d
minor fixes
iliakan Oct 12, 2021
4397c7f
not a right comparison
Jiapan-Yu Oct 21, 2021
c20baa7
Add missing "!"
mahdiHash Oct 21, 2021
db074cd
Remove redundant word in Possible Mistakes section
vigu86 Oct 22, 2021
e0624c3
Update article.md
dneey Oct 22, 2021
1310d54
fix typo
KennethKinLum Oct 23, 2021
4c2658d
Fixed a grammatical error
zaibugemi Oct 24, 2021
6250c91
Merge pull request #1 from zaibugemi/zaibugemi-patch-1
zaibugemi Oct 24, 2021
3699f73
async-await on top
iliakan Oct 25, 2021
277fbd2
Merge pull request #2762 from zaibugemi/master
iliakan Oct 25, 2021
2a5c881
minor fixes
iliakan Oct 25, 2021
e95cab9
Merge pull request #2741 from joneskj55/patch-1
iliakan Oct 25, 2021
51be747
Merge pull request #2744 from LexaWin/patch-1
iliakan Oct 25, 2021
aed8070
Merge pull request #2750 from Jiapan-Yu/master
iliakan Oct 25, 2021
20da240
Merge pull request #2751 from mahdiHashemi14/master
iliakan Oct 25, 2021
3c62ecc
Merge pull request #2753 from vigu86/patch-1
iliakan Oct 25, 2021
676319d
Merge pull request #2755 from dneey/patch-2
iliakan Oct 25, 2021
3efe4cf
Merge pull request #2759 from KennethKinLum/patch-14
iliakan Oct 25, 2021
9dc5f3e
minor fixes
iliakan Oct 25, 2021
91e9b9c
minor fixes
iliakan Oct 25, 2021
6be354d
minor fixes
iliakan Oct 25, 2021
2ac7526
minor fixes
iliakan Oct 25, 2021
8308537
closes #2757
iliakan Oct 25, 2021
6989312
closes #2752
iliakan Oct 25, 2021
f9f77a1
Highlighting opening braces for IIFEs
VamsiDevalla Oct 30, 2021
cc18823
minor fixes
iliakan Nov 1, 2021
be69f34
minor fixes
iliakan Nov 1, 2021
9fcffe1
minor fixes
iliakan Nov 1, 2021
15f7acf
minor fixes
iliakan Nov 1, 2021
f8782ac
Update article.md
itaileshem Nov 2, 2021
e431006
Update article.md
itaileshem Nov 2, 2021
d4ee188
Update article.md
itaileshem Nov 2, 2021
e4c5707
Update article.md
itaileshem Nov 2, 2021
4541b7a
minor fixes
iliakan Nov 3, 2021
a829155
minor fixes
iliakan Nov 12, 2021
3d9f1c9
Update script.js
LexaWin Nov 15, 2021
83d2003
added showStep method to our chain in the task
Tofpu Nov 16, 2021
690c223
added showStep to our chain in the solution
Tofpu Nov 16, 2021
caf1a65
fix the broken RFC link
Dec 2, 2021
762d0e5
Added reference link to mdn docs for Object.keys(user)
akxavier Dec 6, 2021
c574391
Update article.md
yangsong97 Dec 11, 2021
64da7ff
minor fixes
iliakan Dec 12, 2021
df72ada
Merge pull request #2789 from yangsong97/patch-1
iliakan Dec 12, 2021
153fd11
Merge pull request #2783 from akxavier/master
iliakan Dec 12, 2021
a521d20
minor fixes
iliakan Dec 12, 2021
3a34345
Merge pull request #2767 from VamsiDevalla/patch-1
iliakan Dec 12, 2021
fe63de8
Merge pull request #2776 from LexaWin/patch-2
iliakan Dec 12, 2021
747fc37
Merge pull request #2771 from itaileshem/fix-typo
iliakan Dec 12, 2021
2d80f86
Merge pull request #2770 from itaileshem/master
iliakan Dec 12, 2021
e6512a3
Merge pull request #2781 from chanjsq/patch-1
iliakan Dec 12, 2021
c5358c5
themable pictures
iliakan Dec 12, 2021
cf2ce5e
Type: touch-events should be touch-action
justforuse Dec 13, 2021
7e575de
Merge pull request #2792 from justforuse/patch-1
iliakan Dec 13, 2021
cbdb218
Merge pull request #2777 from Tofpu/missing-showstep-patch
iliakan Dec 13, 2021
92a8a40
addition-of-third-header-in-list
Manik2375 Dec 13, 2021
353c87d
typo
Manik2375 Dec 13, 2021
974073b
typeof
iliakan Dec 13, 2021
9a42577
minor fixes
iliakan Dec 13, 2021
b0e46f4
minor fixes
iliakan Dec 13, 2021
80148c0
minor fixes
iliakan Dec 13, 2021
233d63c
minor fixes
iliakan Dec 13, 2021
4bd4a74
minor fixes
iliakan Dec 13, 2021
98d590b
minor fixes
iliakan Dec 13, 2021
8d04d0d
minor fixes
iliakan Dec 13, 2021
e7c5d13
typo
joaquinelio Dec 13, 2021
dc6be3a
Update article.md
joaquinelio Dec 13, 2021
e715c5a
transl: easier to change where mdn: dsnt work
joaquinelio Dec 14, 2021
6fe40fc
Changed a word in article.md
yasledesma Dec 15, 2021
e9e06a5
Fix: Rewrite sentence in line 121
yasledesma Dec 16, 2021
8536bca
fix the broken RFC link in the JSON article
tburette Dec 20, 2021
53488ee
Replace 'mdn' link
odsantos Dec 20, 2021
1ee53e6
Merge pull request #2802 from odsantos/inheritance-fix-link
iliakan Dec 21, 2021
05336f1
Merge pull request #2794 from Manik2375/master
iliakan Dec 21, 2021
96bd8cf
Merge pull request #2795 from joaquinelio/patch-5
iliakan Dec 21, 2021
affee18
Merge pull request #2796 from joaquinelio/patch-8
iliakan Dec 21, 2021
ad70374
Merge pull request #2798 from HiddenOgre28/patch-1
iliakan Dec 21, 2021
3ee59f0
Merge pull request #2801 from tburette/master
iliakan Dec 21, 2021
25d51b1
Merge pull request #2800 from HiddenOgre28/patch-2
iliakan Dec 21, 2021
199e412
Fix sentence
tathienphuoc Dec 21, 2021
ad0df99
Update article.md
joaquinelio Dec 24, 2021
0cd40ae
Merge pull request #2564 from joaquinelio/patch-10
iliakan Dec 24, 2021
3c934b5
minor fixes
Dec 24, 2021
3aaa6fc
foolproof
joaquinelio Jan 9, 2022
246c600
Merge pull request #2819 from joaquinelio/patch-12
iliakan Jan 9, 2022
de83e74
Update article.md
NickFallman Jan 10, 2022
610fb93
Merge pull request #2820 from NickFallman/patch-1
iliakan Jan 10, 2022
421bbe5
Update article.md
11201010 Jan 15, 2022
ffcd381
Merge pull request #2803 from tathienphuoc/master
iliakan Jan 16, 2022
a6fdfda
Merge pull request #2828 from 11201010/master
iliakan Jan 16, 2022
286a142
merging all conflicts
iliakan Jan 17, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
* text=auto eol=lf
*.svg binary
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -21,3 +21,4 @@ sftp-config.json
Thumbs.db


/svgs
34 changes: 18 additions & 16 deletions 1-js/01-getting-started/1-intro/article.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# 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 what other technologies play well with it.

## What is JavaScript?

*JavaScript* was initially created to *"make web pages alive"*.
*JavaScript* was initially created to "make web pages alive".

The programs in this language are called *scripts*. They can be written right in a web page's HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don't need special preparation or compilation to run.

In this aspect, JavaScript is very different from another language called [Java](https://en.wikipedia.org/wiki/Java_(programming_language)).

```smart header="Why <u>Java</u>Script?"
```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.
@@ -24,11 +24,11 @@ The browser has an embedded engine sometimes called a "JavaScript virtual machin

Different engines have different "codenames". For example:

- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome and Opera.
- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome, Opera and Edge.
- [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- in Firefox.
- ...There are other codenames like "Trident" and "Chakra" for different versions of IE, "ChakraCore" for Microsoft Edge, "Nitro" and "SquirrelFish" for Safari, etc.
- ...There are other codenames like "Chakra" for IE, "JavaScriptCore", "Nitro" and "SquirrelFish" for Safari, etc.

The terms above are good to remember because they are used in developer articles on the internet. We'll use them too. For instance, if "a feature X is supported by V8", then it probably works in Chrome 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, Opera and Edge.

```smart header="How do engines work?"
@@ -38,7 +38,7 @@ 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 at each step 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. When it's done, scripts run 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?
@@ -59,11 +59,11 @@ For instance, in-browser JavaScript is able to:

## What CAN'T in-browser JavaScript do?

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.
JavaScript's abilities in the browser are limited for the sake of a user's safety. The aim is to prevent an evil webpage from accessing private information or harming the user's data.

Examples of such restrictions include:

- JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS system functions.
- JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS functions.

Modern browsers allow it to work with files, but the access is limited and only provided if the user does certain actions, like "dropping" a file into a browser window or selecting it via an `<input>` tag.

@@ -86,14 +86,13 @@ There are at least *three* great things about JavaScript:
```compare
+ Full integration with HTML/CSS.
+ Simple things are done simply.
+ Support by all major browsers and enabled by default.
+ Supported by all major browsers and enabled by default.
```
JavaScript is the only browser technology that combines these three things.

That's what makes JavaScript unique. That's why it's the most widespread tool for creating browser interfaces.

While planning to learn a new technology, it's beneficial to check its perspectives. So let's move on to the modern trends affecting it, including new languages and browser abilities.

That said, JavaScript also allows to create servers, mobile applications, etc.

## Languages "over" JavaScript

@@ -109,12 +108,15 @@ Examples of such languages:

- [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.
- [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.
- [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.
- [Brython](https://brython.info/) is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript.
- [Kotlin](https://kotlinlang.org/docs/reference/js-overview.html) is a modern, concise and safe programming language that can target the browser or Node.

There are more. Of course, even if we use one of these 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 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.
- JavaScript was initially created as a browser-only language, but it is now used in many other environments as well.
- Today, JavaScript has a unique position as the most widely-adopted browser language, fully integrated with HTML/CSS.
- There are many languages that get "transpiled" to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript.
37 changes: 37 additions & 0 deletions 1-js/01-getting-started/2-manuals-specifications/article.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

# 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 developing for the browser, then there are other specifications covered in the [second part](info:browser-environment) of the tutorial.

## Manuals

- **MDN (Mozilla) JavaScript Reference** is the main manual with examples and other information. It's great to get in-depth information about individual language functions, methods etc.

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.

## 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.
Original file line number Diff line number Diff line change
@@ -12,14 +12,12 @@ An IDE loads the project (which can be many files), allows navigation between fi

If you haven't selected an IDE yet, consider the following options:

- [WebStorm](http://www.jetbrains.com/webstorm/) for frontend development. The same company offers other editors for other languages (paid).
- [Netbeans](http://netbeans.org/) (free).
- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free).
- [WebStorm](http://www.jetbrains.com/webstorm/) (cross-platform, paid).

All of these IDEs are cross-platform.
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/).

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. A free version of it is called [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.
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

@@ -33,21 +31,11 @@ In practice, lightweight editors may have a lot of plugins including directory-l

The following options deserve your attention:

- [Visual Studio Code](https://code.visualstudio.com/) (cross-platform, free) also has many IDE-like features.
- [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:

- As an IDE for JS -- [WebStorm](http://www.jetbrains.com/webstorm/) (I switch to one of the other JetBrains offerings when using other languages)
- 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 whom I consider good developers have been using for a long time and are happy with.
Binary file removed 1-js/01-getting-started/3-devtools/safari.png
Binary file not shown.
Binary file removed 1-js/01-getting-started/3-devtools/safari@2x.png
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -29,10 +29,15 @@ The exact look of developer tools depends on your version of Chrome. It changes
- 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 (`key:Shift+Enter` to input multi-line commands).
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

@@ -50,12 +55,6 @@ Open Preferences and go to the "Advanced" pane. There's a checkbox at the bottom

Now `key:Cmd+Opt+C` can toggle the console. Also, note that the new top menu item named "Develop" has appeared. It has many commands and options.

## Multi-line input

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`.

## Summary

- Developer tools allow us to see errors, run commands, examine variables, and much more.
File renamed without changes.
Binary file added 1-js/01-getting-started/4-devtools/safari.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 1-js/01-getting-started/4-devtools/safari@2x.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions 1-js/02-first-steps/01-hello-world/1-hello-alert/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>

<body>

<script>
alert( "I'm JavaScript!" );
</script>

</body>

</html>
2 changes: 2 additions & 0 deletions 1-js/02-first-steps/01-hello-world/1-hello-alert/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

[html src="index.html"]
14 changes: 6 additions & 8 deletions 1-js/02-first-steps/01-hello-world/article.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Hello, world!

This part of the tutorial is about core JavaScript, the language itself. Later on, you'll learn about Node.js and other platforms that use it.
This part of the tutorial is about core JavaScript, the language itself.

But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like `alert`) to a minimum so that you don't spend time on them if you plan to concentrate on another environment (like Node.js). We'll focus on JavaScript in the browser in the [next part](/ui) of the tutorial.

@@ -9,7 +9,7 @@ So first, let's see how we attach a script to a webpage. For server-side environ

## The "script" tag

JavaScript programs can be inserted into any part of an HTML document with the help of the `<script>` tag.
JavaScript programs can be inserted almost anywhere into an HTML document using the `<script>` tag.

For instance:

@@ -46,7 +46,7 @@ The `<script>` tag contains JavaScript code which is automatically executed when
The `<script>` tag has a few attributes that are rarely used nowadays but can still be found in old code:

The `type` attribute: <code>&lt;script <u>type</u>=...&gt;</code>
: The old HTML standard, HTML4, required a script to have a `type`. Usually it was `type="text/javascript"`. It's not required anymore. Also, the modern HTML standard, HTML5, totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic; we'll talk about modules in another part of the tutorial.
: The old HTML standard, HTML4, required a script to have a `type`. Usually it was `type="text/javascript"`. It's not required anymore. Also, the modern HTML standard totally changed the meaning of this attribute. Now, it can be used for JavaScript modules. But that's an advanced topic, we'll talk about modules in another part of the tutorial.

The `language` attribute: <code>&lt;script <u>language</u>=...&gt;</code>
: 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.
@@ -60,7 +60,7 @@ Comments before and after scripts.
//--></script>
```

This trick isn't used in modern JavaScript. These comments hid 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.
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
@@ -73,14 +73,12 @@ Script files are attached to HTML with the `src` attribute:
<script src="/path/to/script.js"></script>
```

Here, `/path/to/script.js` is an absolute path to the script file (from the site root).

You can also provide a relative path from the current page. For instance, `src="script.js"` would mean a file `"script.js"` in the current folder.
Here, `/path/to/script.js` is an absolute path to the script from the site root. One can also provide a relative path from the current page. For instance, `src="script.js"`, just like `src="./script.js"`, would mean a file `"script.js"` in the current folder.

We can give a full URL as well. For instance:

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
```

To attach several scripts, use multiple tags:
40 changes: 18 additions & 22 deletions 1-js/02-first-steps/02-structure/article.md
Original file line number Diff line number Diff line change
@@ -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", so the semicolon is not 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 a semicolon there would be incorrect. And in this case, that works as intended.

**But there are situations where JavaScript "fails" to assume a semicolon where it is really needed.**

@@ -56,45 +56,41 @@ Errors which occur in such cases are quite hard to find and fix.
If you're curious to see a concrete example of such an error, check this code out:
```js run
[1, 2].forEach(alert)
alert("Hello");
[1, 2].forEach(alert);
```
No need to think about the meaning of the brackets `[]` and `forEach` yet. We'll study them later. For now, just remember the result of the code: 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 running the code: it shows `Hello`, then `1`, then `2`.
Now, let's add an `alert` before the code and *not* finish it with a semicolon:
Now let's remove the semicolon after the `alert`:
```js run no-beautify
alert("There will be an error")
alert("Hello")
[1, 2].forEach(alert)
[1, 2].forEach(alert);
```
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
alert("All fine now");
The difference compared to the code above is only one character: the semicolon at the end of the first line is gone.
[1, 2].forEach(alert)
```
If we run this code, only the first `Hello` shows (and there's an error, you may need to open the console to see it). There are no numbers any more.
Now we have the "All fine now" message followed by `1` and `2`.
That's because JavaScript does not assume a semicolon before square brackets `[...]`. So, the code in the last example is treated as a single statement.
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. Here's how the engine sees it:
Here's how the engine sees it:
```js run no-beautify
alert("There will be an error")[1, 2].forEach(alert)
alert("Hello")[1, 2].forEach(alert);
```
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.
Looks weird, right? Such merging in this case is just wrong. We need to put a semicolon after `alert` for the code to work correctly.
This can happen in other situations also.
````

We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let's note once again -- *it is possible* to leave out semicolons most of the time. But it's safer -- especially for a beginner -- to use them.

## Comments
## Comments [#code-comments]

As time goes on, programs become more and more complex. It becomes necessary to add *comments* which describe what the code does and why.

@@ -136,7 +132,7 @@ alert('World');
```

```smart header="Use hotkeys!"
In most editors, a line of code can be commented out by pressing the `key:Ctrl+/` hotkey for a single-line comment and something like `key:Ctrl+Shift+/` -- for multiline comments (select a piece of code and press the hotkey). For Mac, try `key:Cmd` instead of `key:Ctrl`.
In most editors, a line of code can be commented out by pressing the `key:Ctrl+/` hotkey for a single-line comment and something like `key:Ctrl+Shift+/` -- for multiline comments (select a piece of code and press the hotkey). For Mac, try `key:Cmd` instead of `key:Ctrl` and `key:Option` instead of `key:Shift`.
```

````warn header="Nested comments are not supported!"
38 changes: 20 additions & 18 deletions 1-js/02-first-steps/03-strict-mode/article.md
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ For a long time, JavaScript evolved without compatibility issues. New features w

That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript's creators got stuck in the language forever.

This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`.
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most such modifications are off by default. You need to explicitly enable them with a special directive: `"use strict"`.

## "use strict"

@@ -19,10 +19,7 @@ For example:
...
```

We will learn functions (a way to group commands) soon.

Looking ahead, let's just note that `"use strict"` can be put at the start of most kinds of functions instead of the whole script. Doing that enables strict mode in that function only. But usually, people use it for the whole script.

Quite soon we're going to learn functions (a way to group commands), so let's note in advance that `"use strict"` can be put at the beginning of a function. Doing that enables strict mode in that function only. But usually people use it for the whole script.

````warn header="Ensure that \"use strict\" is at the top"
Please make sure that `"use strict"` is at the top of your scripts, otherwise strict mode may not be enabled.
@@ -44,16 +41,18 @@ Only comments may appear above `"use strict"`.
```warn header="There's no way to cancel `use strict`"
There is no directive like `"no use strict"` that reverts the engine to old behavior.

Once we enter strict mode, there's no 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.
When you use a [developer console](info:devtools) to run code, please note that it doesn't `use strict` by default.
Sometimes, when `use strict` makes a difference, you'll get incorrect results.
You can try to press `key:Shift+Enter` to input multiple lines, and put `use strict` on top, like this:
So, how to actually `use strict` in the console?
First, you can try to press `key:Shift+Enter` to input multiple lines, and put `use strict` on top, like this:
```js
'use strict'; <Shift+Enter for a newline>
@@ -63,25 +62,28 @@ You can try to press `key:Shift+Enter` to input multiple lines, and put `use str

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:
If it doesn't, e.g. in an old browser, there's an ugly, but reliable way to ensure `use strict`. Put it inside this kind of wrapper:

```js
(function() {
'use strict';

// ...your code...
// ...your code here...
})()
```

## Always "use strict"
## Should we "use strict"?

The question may sound obvious, but it's not so.

One could recommend to start scripts with `"use strict"`... But you know what's cool?

Modern JavaScript supports "classes" and "modules" - advanced language structures (we'll surely get to them), that enable `use strict` automatically. So we don't need to add the `"use strict"` directive, if we use them.

We have yet to cover the differences between strict mode and the "default" mode.
**So, for now `"use strict";` is a welcome guest at the top of your scripts. Later, when your code is all in classes and modules, you may omit it.**

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.
As of now, we've got to know about `use strict` in general.

For now, it's enough to know about it in general:
In the next chapters, as we learn language features, we'll see the differences between the strict and old modes. Luckily, there aren't many and they actually make our lives better.

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.
All examples in this tutorial assume strict mode unless (very rarely) specified otherwise.
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
First, the variable for the name of our planet.
## The variable for our planet

That's simple:

```js
let ourPlanetName = "Earth";
```

Note, we could use a shorter name `planet`, but it might be not obvious what planet it refers to. It's nice to be more verbose. At least until the variable isNotTooLong.
Note, we could use a shorter name `planet`, but it might not be 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";
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 20 additions & 7 deletions 1-js/02-first-steps/04-variables/article.md
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ A [variable](https://en.wikipedia.org/wiki/Variable_(computer_science)) is a "na

To create a variable in JavaScript, use the `let` keyword.

The statement below creates (in other words: *declares* or *defines*) a variable with the name "message":
The statement below creates (in other words: *declares*) a variable with the name "message":

```js
let message;
@@ -24,7 +24,7 @@ Now, we can put some data into it by using the assignment operator `=`:
let message;

*!*
message = 'Hello'; // store the string
message = 'Hello'; // store the string 'Hello' in the variable named message
*/!*
```

@@ -80,7 +80,6 @@ let user = 'John'

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`:

@@ -135,6 +134,20 @@ alert(hello); // Hello world!
alert(message); // Hello world!
```
````warn header="Declaring twice triggers an error"
A variable should be declared only once.
A repeated declaration of the same variable is an error:
```js run
let message = "This";
// repeated 'let' leads to an error
let message = "That"; // SyntaxError: 'message' has already been declared
```
So, we should declare a variable once and then refer to it without `let`.
````

```smart header="Functional languages"
It's interesting to note that there exist [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.
@@ -190,7 +203,7 @@ let имя = '...';
let 我 = '...';
```
Technically, there is no error here, such names are allowed, but there is an international tradition to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
````

````warn header="Reserved names"
@@ -237,7 +250,7 @@ To declare a constant (unchanging) variable, use `const` instead of `let`:
const myBirthday = '18.04.1982';
```
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do so 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';
@@ -290,7 +303,7 @@ In other words, capital-named constants are only used as aliases for "hard-coded
Talking about variables, there's one more extremely important thing.
A variable name should have a clean, obvious meaning, describe the data that it stores.
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 was written by a beginner versus an experienced developer.
@@ -323,7 +336,7 @@ Modern JavaScript minifiers and browsers optimize code well enough, so it won't
We can declare variables to store data by using the `var`, `let`, or `const` keywords.
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
- `let` -- is a modern variable declaration.
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
- `const` -- is like `let`, but the value of the variable can't be changed.
104 changes: 69 additions & 35 deletions 1-js/02-first-steps/05-types/article.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
# Data types

A variable in JavaScript can contain any data. A variable can at one moment be a string and at another be a number:
A value in JavaScript is always of a certain type. For example, a string or a number.

There are eight basic data types in JavaScript. Here, we'll cover them in general and in the next chapters we'll talk about each of them in detail.

We can put any type in a variable. For example, a variable can at one moment be a string and then store a number:

```js
// no error
let message = "hello";
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.
Programming languages that allow such things, such as JavaScript, are called "dynamically typed", meaning that there exist data types, but variables are not bound to any of them.

There are seven 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;
@@ -62,14 +64,38 @@ Special numeric values formally belong to the "number" type. Of course they are

We'll see more about working with numbers in the chapter <info:number>.

## A string
## BigInt [#bigint-type]

In JavaScript, the "number" type cannot represent integer values larger than <code>(2<sup>53</sup>-1)</code> (that's `9007199254740991`), or less than <code>-(2<sup>53</sup>-1)</code> for negatives. It's a technical limitation caused by their internal representation.

For most purposes that's quite enough, 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` value is created by appending `n` to the end of an integer:

```js
// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;
```

As `BigInt` numbers are rarely needed, we don't cover them here, but devoted them a separate chapter <info:bigint>. Read it when you need such big numbers.


```smart header="Compatibility issues"
Right now, `BigInt` is supported in Firefox/Chrome/Edge/Safari, but not in IE.
```

You can check [*MDN* BigInt compatibility table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#Browser_compatibility) to know which versions of a browser are supported.

## 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 +104,7 @@ In JavaScript, there are 3 types of quotes.
2. Single quotes: `'Hello'`.
3. Backticks: <code>&#96;Hello&#96;</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:

@@ -102,12 +128,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.
In JavaScript, there is no such type. There's only one type: `string`. A string may consist of zero characters (be empty), one character or many of them.
```

## A boolean (logical type)
## Boolean (logical type)

The boolean type has only two values: `true` and `false`.

@@ -144,7 +170,7 @@ In JavaScript, `null` is not a "reference to a non-existing object" or a "null p

It's just a special value which represents "nothing", "empty" or "value unknown".

The code above states that `age` is unknown or empty for some reason.
The code above states that `age` is unknown.

## The "undefined" value

@@ -155,49 +181,47 @@ The meaning of `undefined` is "value is not assigned".
If a variable is declared, but not assigned, then its value is `undefined`:

```js run
let x;
let age;

alert(x); // shows "undefined"
alert(age); // shows "undefined"
```

Technically, it is possible to assign `undefined` to any variable:
Technically, it is possible to explicitly assign `undefined` to a variable:

```js run
let x = 123;
let age = 100;

x = undefined;
// change the value to undefined
age = undefined;

alert(x); // "undefined"
alert(age); // "undefined"
```

...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.
...But we don't recommend doing that. Normally, one uses `null` to assign an "empty" or "unknown" value to a variable, while `undefined` is reserved as a default initial value for unassigned things.

## 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 learn more about primitives.
All other types are called "primitive" because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities.

The `symbol` type is used to create unique identifiers for objects. We have to mention it here for completeness, but it's better to study this type after objects.
Being that important, objects deserve a special treatment. 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 the sake of completeness, but also postpone the details till we know 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 do a quick check.

It supports two forms of syntax:

1. As an operator: `typeof x`.
2. As a function: `typeof(x)`.

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:
A call to `typeof x` returns a string with the type name:

```js
typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"
@@ -220,16 +244,26 @@ typeof alert // "function" (3)
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 of the language. We'll study functions in the next chapters where we'll see that there's no special "function" type in JavaScript. Functions belong to the object type. But `typeof` treats them differently. Formally, it's incorrect, but very convenient in practice.
2. The result of `typeof null` is `"object"`. That's an officially recognized error in `typeof`, coming from very early days of JavaScript and kept for compatibility. Definitely, `null` is not an object. It is a special value with a separate type of its own. The behavior of `typeof` is wrong here.
3. The result of `typeof alert` is `"function"`, because `alert` is a function. We'll study functions in the next chapters where we'll also see that there's no special "function" type in JavaScript. Functions belong to the object type. But `typeof` treats them differently, returning `"function"`. That also comes from the early days of JavaScript. Technically, such behavior isn't correct, but can be convenient in practice.

```smart header="The `typeof(x)` syntax"
You may also come across another syntax: `typeof(x)`. It's the same as `typeof x`.

To put it clear: `typeof` is an operator, not a function. The parentheses here aren't a part of `typeof`. It's the kind of parentheses used for mathematical grouping.

Usually, such parentheses contain a mathematical expression, such as `(2 + 2)`, but here they contain only one argument `(x)`. Syntactically, they allow to avoid a space between the `typeof` operator and its argument, and some people like it.

Some people prefer `typeof(x)`, although the `typeof x` syntax is much more common.
```
## Summary
There are 7 basic data types in JavaScript.
There are 8 basic data types in JavaScript.
- `number` for numbers of any kind: integer or floating-point.
- `string` for strings. A string may have one or more characters, there's no separate single-character type.
- `number` for numbers of any kind: integer or floating-point, integers are limited by <code>±(2<sup>53</sup>-1)</code>.
- `bigint` is for integer numbers of arbitrary length.
- `string` for strings. A string may have zero or more characters, there's no separate single-character type.
- `boolean` for `true`/`false`.
- `null` for unknown values -- a standalone type that has a single value `null`.
- `undefined` for unassigned values -- a standalone type that has a single value `undefined`.
@@ -238,7 +272,7 @@ There are 7 basic data types in JavaScript.
The `typeof` operator allows us to see which type is stored in a variable.
- Two forms: `typeof x` or `typeof(x)`.
- Usually used as `typeof x`, but `typeof(x)` is also possible.
- Returns a string with the name of the type, like `"string"`.
- For `null` returns `"object"` -- this is an error in the language, it's not actually an object.
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
# Interaction: alert, prompt, confirm

In this part of the tutorial we cover JavaScript language "as is", without environment-specific tweaks.

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`.
As we'll be using the browser as our demo environment, let's see a couple of functions to interact with the user: `alert`, `prompt` and `confirm`.

## alert

Syntax:

```js
alert(message);
```

This shows a message and pauses script execution until the user presses "OK".
This one we've seen already. It shows a message and waits for the user to press "OK".

For example:

```js run
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

@@ -30,15 +22,19 @@ The function `prompt` accepts two arguments:
result = prompt(title, [default]);
```

It shows a modal window with a text message, an input field for the visitor, and the buttons OK/CANCEL.
It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.

`title`
: The text to show the visitor.

`default`
: An optional second parameter, the initial value for the input field.

The visitor may type something in the prompt input field and press OK. Or they can cancel the input by pressing CANCEL or hitting the `key:Esc` key.
```smart header="The square brackets in syntax `[...]`"
The square brackets around `default` in the syntax above denote that the parameter is optional, not required.
```
The visitor can type something in the prompt input field and press OK. Then we get that text in the `result`. Or they can cancel the input by pressing Cancel or hitting the `key:Esc` key, then we get `null` as the `result`.
The call to `prompt` returns the text from the input field or `null` if the input was canceled.
@@ -74,7 +70,7 @@ The syntax:
result = confirm(question);
```
The function `confirm` shows a modal window with a `question` and two buttons: OK and CANCEL.
The function `confirm` shows a modal window with a `question` and two buttons: OK and Cancel.
The result is `true` if OK is pressed and `false` otherwise.
@@ -94,10 +90,10 @@ We covered 3 browser-specific functions to interact with visitors:
: shows a message.
`prompt`
: shows a message asking the user to input text. It returns the text or, if CANCEL or `key:Esc` is clicked, `null`.
: shows a message asking the user to input text. It returns the text or, if Cancel button or `key:Esc` is clicked, `null`.
`confirm`
: shows a message and waits for the user to press "OK" or "CANCEL". It returns `true` for OK and `false` for CANCEL/`key:Esc`.
: shows a message and waits for the user to press "OK" or "Cancel". It returns `true` for OK and `false` for Cancel/`key:Esc`.
All these methods are modal: they pause script execution and don't allow the visitor to interact with the rest of the page until the window has been dismissed.
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
# Type Conversions

Most of the time, operators and functions automatically convert the values given to them to the right type.
Most of the time, operators and functions automatically convert the values given to them to the right type.

For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers.

There are also cases when we need to explicitly convert a value to the expected type.

```smart header="Not talking about objects yet"
In this chapter, we won't cover objects. 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>.
In this chapter, we won't cover objects. For now we'll just be talking about primitives.
Later, after we learn about objects, in the chapter <info:object-toprimitive> we'll see how objects fit in.
```

## ToString
## String Conversion

String conversion happens when we need the string form of a value.

@@ -30,7 +32,7 @@ alert(typeof value); // string

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.

@@ -81,20 +83,9 @@ alert( Number(false) ); // 0

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. A notable exception is addition `+`. If one of the added values is a string, the other one is also converted to a string.
Then, it concatenates (joins) them:
```js run
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
```
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
````
Most mathematical operators also perform such conversion, we'll see that in the next chapter.

## ToBoolean
## Boolean Conversion

Boolean conversion is the simplest one.

@@ -124,14 +115,13 @@ alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
```
````
## Summary
The three most widely used type conversions are to string, to number, and to boolean.
**`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 +132,7 @@ The conversion follows the rules:
|<code>true&nbsp;/&nbsp;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. Can be performed with `Boolean(value)`.
**`Boolean Conversion`** -- Occurs in logical operations. Can be performed with `Boolean(value)`.
Follows the rules:

This file was deleted.

Original file line number Diff line number Diff line change
@@ -9,11 +9,11 @@ true + false = 1
"$" + 4 + 5 = "$45"
"4" - 2 = 2
"4px" - 2 = NaN
7 / 0 = Infinity
" -9 " + 5 = " -9 5" // (3)
" -9 " - 5 = -14 // (4)
" -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.
@@ -22,3 +22,4 @@ undefined + 1 = NaN // (6)
4. The subtraction always converts to numbers, so it makes `" -9 "` a number `-9` (ignoring spaces around it).
5. `null` becomes `0` after the numeric conversion.
6. `undefined` becomes `NaN` after the numeric conversion.
7. Space characters, are trimmed off string start and end when a string is converted to a number. Here the whole string consists of space characters, such as `\t`, `\n` and a "regular" space between them. So, similarly to an empty string, it becomes `0`.
Original file line number Diff line number Diff line change
@@ -16,11 +16,11 @@ true + false
"$" + 4 + 5
"4" - 2
"4px" - 2
7 / 0
" -9 " + 5
" -9 " - 5
null + 1
undefined + 1
" \t \n" - 2
```

Think well, write down and then compare with the answer.
32 changes: 32 additions & 0 deletions 1-js/02-first-steps/08-operators/4-fix-prompt/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
The reason is that prompt returns user input as a string.

So variables have values `"1"` and `"2"` respectively.

```js run
let a = "1"; // prompt("First number?", 1);
let b = "2"; // prompt("Second number?", 2);

alert(a + b); // 12
```

What we should do is to convert strings to numbers before `+`. For example, using `Number()` or prepending them with `+`.

For example, right before `prompt`:

```js run
let a = +prompt("First number?", 1);
let b = +prompt("Second number?", 2);

alert(a + b); // 3
```

Or in the `alert`:

```js run
let a = prompt("First number?", 1);
let b = prompt("Second number?", 2);

alert(+a + +b); // 3
```

Using both unary and binary `+` in the latest code. Looks funny, doesn't it?
18 changes: 18 additions & 0 deletions 1-js/02-first-steps/08-operators/4-fix-prompt/task.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
importance: 5

---

# Fix the addition

Here's a code that asks the user for two numbers and shows their sum.

It works incorrectly. The output in the example below is `12` (for default prompt values).

Why? Fix it. The result should be `3`.

```js run
let a = prompt("First number?", 1);
let b = prompt("Second number?", 2);

alert(a + b); // 12
```
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Operators
# Basic operators, maths

We know many operators from school. They are things like addition `+`, multiplication `*`, subtraction `-`, and so on.

In this chapter, we'll concentrate on aspects of operators that are not covered by school arithmetic.
In this chapter, well start with simple operators, then concentrate on JavaScript-specific aspects, not covered by school arithmetic.

## Terms: "unary", "binary", "operand"

@@ -26,11 +26,61 @@ Before we move on, let's grasp some common terminology.
alert( y - x ); // 2, binary minus subtracts values
```

Formally, we're talking about two different operators here: the unary negation (single operand: reverses the sign) and the binary subtraction (two operands: subtracts).
Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction operator, a binary operator that subtracts one number from another.

## String concatenation, binary +
## Maths

Now, let's see special features of JavaScript operators that are beyond school arithmetics.
The following math operations are supported:

- Addition `+`,
- Subtraction `-`,
- Multiplication `*`,
- Division `/`,
- Remainder `%`,
- Exponentiation `**`.

The first four are straightforward, while `%` and `**` need a few words about them.

### Remainder %

The remainder operator `%`, despite its appearance, is not related to percents.

The result of `a % b` is the [remainder](https://en.wikipedia.org/wiki/Remainder) of the integer division of `a` by `b`.

For instance:

```js run
alert( 5 % 2 ); // 1, a remainder of 5 divided by 2
alert( 8 % 3 ); // 2, a remainder of 8 divided by 3
```

### Exponentiation **

The exponentiation operator `a ** b` raises `a` to the power of `b`.

In school maths, we write that as a<sup>b</sup>.

For instance:

```js run
alert( 2 ** 2 ); // 2² = 4
alert( 2 ** 3 ); // 2³ = 8
alert( 2 ** 4 ); // 2⁴ = 16
```

Just like in maths, the exponentiation operator is defined for non-integer numbers as well.

For example, a square root is an exponentiation by ½:

```js run
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
```


## String concatenation with binary +

Let's meet features of JavaScript operators that are beyond school arithmetics.
Usually, the plus operator `+` sums numbers.
@@ -41,7 +91,7 @@ let s = "my" + "string";
alert(s); // mystring
```
Note that if one of the operands is a string, the other one is converted to a string too.
Note that if any of the operands is a string, then the other one is converted to a string too.
For example:
@@ -50,22 +100,28 @@ 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, 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:
See, it doesn't matter whether the first operand is a string or the second one.

Here's a more complex example:
```js run
alert(2 + 2 + '1' ); // "41" and not "221"
```
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.
Here, operators work one after another. The first `+` sums two numbers, so it returns `4`, then the next `+` adds the string `1` to it, so it's like `4 + '1' = '41'`.

```js run
alert('1' + 2 + 2); // "122" and not "14"
```
Here, the first operand is a string, the compiler treats the other two operands as strings too. The `2` gets concatenated to `'1'`, so it's like `'1' + 2 = "12"` and `"12" + 2 = "122"`.
For instance, subtraction and division:
The binary `+` is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.
Here's the demo for subtraction and division:

```js run
alert( 2 - '1' ); // 1
alert( '6' / '2' ); // 3
alert( 6 - '2' ); // 4, converts '2' to a number
alert( '6' / '2' ); // 3, converts both operands to numbers
```

## Numeric conversion, unary +
@@ -93,9 +149,7 @@ alert( +"" ); // 0
It actually does the same thing as `Number(...)`, but is shorter.
The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings.

What if we want to sum them?
The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?
The binary plus would add them as strings:
@@ -127,30 +181,31 @@ Why are unary pluses applied to values before the binary ones? As we're going to

## Operator precedence

If an expression has more than one operator, the execution order is defined by their *precedence*, or, in other words, the implicit priority order of 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.
Parentheses override any precedence, so if we're not satisfied with the implicit order, we can use them to change it. For example: `(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 larger number executes first. If the precedence is the same, the execution order is from left to right.

Here's an extract from the [precedence table](https://developer.mozilla.org/en/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-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) (you don't need to remember this, but note that unary operators are higher than corresponding binary ones):

| Precedence | Name | Sign |
|------------|------|------|
| ... | ... | ... |
| 16 | unary plus | `+` |
| 16 | unary negation | `-` |
| 14 | multiplication | `*` |
| 14 | division | `/` |
| 17 | unary plus | `+` |
| 17 | unary negation | `-` |
| 16 | exponentiation | `**` |
| 15 | multiplication | `*` |
| 15 | division | `/` |
| 13 | addition | `+` |
| 13 | subtraction | `-` |
| ... | ... | ... |
| 3 | assignment | `=` |
| ... | ... | ... |

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.
As we can see, the "unary plus" has a priority of `17` 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
@@ -164,24 +219,11 @@ let x = 2 * 2 + 1;
alert( x ); // 5
```
It is possible to chain assignments:
```js run
let a, b, c;
*!*
a = b = c = 2 + 2;
*/!*
alert( a ); // 4
alert( b ); // 4
alert( c ); // 4
```
### Assignment = returns a 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.
The fact of `=` being an operator, not a "magical" language construct has an interesting implication.
````smart header="The assignment operator `\"=\"` returns a value"
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.
All operators in JavaScript return a value. That's obvious for `+` and `-`, but also true for `=`.

The call `x = value` writes the `value` into `x` *and then returns it*.

@@ -199,51 +241,76 @@ 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 see it in 3rd-party libraries, but shouldn't write anything like that ourselves. Such tricks definitely don't make code clearer or readable.
````
Funny code, isn't it? We should understand how it works, because sometimes we see it in JavaScript libraries.

## Remainder %
Although, please don't write the code like that. Such tricks definitely don't make code clearer or readable.

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`.
### Chaining assignments

For instance:
Another interesting feature is the ability to chain assignments:

```js run
alert( 5 % 2 ); // 1 is a remainder of 5 divided by 2
alert( 8 % 3 ); // 2 is a remainder of 8 divided by 3
alert( 6 % 3 ); // 0 is a remainder of 6 divided by 3
let a, b, c;
*!*
a = b = c = 2 + 2;
*/!*
alert( a ); // 4
alert( b ); // 4
alert( c ); // 4
```

## Exponentiation **
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.

The exponentiation operator `**` is a recent addition to the language.
Once again, for the purposes of readability it's better to split such code into few lines:
For a natural number `b`, the result of `a ** b` is `a` multiplied by itself `b` times.
```js
c = 2 + 2;
b = c;
a = c;
```
That's easier to read, especially when eye-scanning the code fast.

For instance:
## Modify-in-place

We often need to apply an operator to a variable and store the new result in that same variable.

For example:

```js
let n = 2;
n = n + 5;
n = n * 2;
```

This notation can be shortened using the operators `+=` and `*=`:

```js run
alert( 2 ** 2 ); // 4 (2 * 2)
alert( 2 ** 3 ); // 8 (2 * 2 * 2)
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
```

The operator works for non-integer numbers as well.
Short "modify-and-assign" operators exist for all arithmetical and bitwise operators: `/=`, `-=`, etc.

For instance:
Such operators have the same precedence as a normal assignment, so they run after most other calculations:

```js run
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
let n = 2;
n *= 3 + 5;
alert( n ); // 16 (right part evaluated first, same as n *= 8)
```

## Increment/decrement

<!-- Can't use -- in title, because built-in parse turns it into – -->
<!-- Can't use -- in title, because the built-in parser turns it into a 'long dash' – -->
Increasing or decreasing a number by one is among the most common numerical operations.
@@ -253,14 +320,14 @@ So, there are special operators for it:
```js run no-beautify
let counter = 2;
counter++; // works the same as counter = counter + 1, but is shorter
counter++; // works the same as counter = counter + 1, but is shorter
alert( counter ); // 3
```
- **Decrement** `--` decreases a variable by 1:
```js run no-beautify
let counter = 2;
counter--; // works the same as counter = counter - 1, but is shorter
counter--; // works the same as counter = counter - 1, but is shorter
alert( counter ); // 1
```
@@ -370,41 +437,7 @@ The list of operators:
- RIGHT SHIFT ( `>>` )
- ZERO-FILL RIGHT SHIFT ( `>>>` )
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 that same variable.
For example:
```js
let n = 2;
n = n + 5;
n = n * 2;
```
This notation can be shortened using the operators `+=` and `*=`:
```js run
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
```
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:
```js run
let n = 2;
n *= 3 + 5;
alert( n ); // 16 (right part evaluated first, same as n *= 8)
```
These operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level. We won't need these operators any time soon, as web development has little use of them, but in some special areas, such as cryptography, they are useful. You can read the [Bitwise Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise) chapter on MDN when a need arises.

## Comma

@@ -427,10 +460,10 @@ Here, the first expression `1 + 2` is evaluated and its result is thrown away. T
```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 finally the number after the comma, `7`, is not processed 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 an operator that 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.

@@ -443,4 +476,4 @@ for (*!*a = 1, b = 3, c = a * b*/!*; a < 10; a++) {
}
```

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.
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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@


```js no-beautify
5 > 4true
"apple" > "pineapple"false
"2" > "12"true
undefined == nulltrue
undefined === nullfalse
null == "\n0\n"false
null === +"\n0\n"false
```

Some of the reasons:

1. Obviously, true.
2. Dictionary comparison, hence false. `"a"` is smaller than `"p"`.
3. Again, dictionary comparison, first char `"2"` is greater than the first char `"1"`.
4. Values `null` and `undefined` equal each other only.
5. Strict equality is strict. Different types from both sides lead to false.
6. Similar to `(4)`, `null` only equals `undefined`.
7. Strict equality of different types.
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
# Comparisons

We know many comparison operators from maths:
We know many comparison operators from maths.

In JavaScript they are written like this:

- Greater/less than: <code>a &gt; b</code>, <code>a &lt; b</code>.
- Greater/less than or equals: <code>a &gt;= b</code>, <code>a &lt;= 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>&ne;</code>, but 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 equality sign `==` means the equality test, while a single one `a = b` means an assignment.
- Not equals: In maths the notation is <code>&ne;</code>, but in JavaScript it's written as <code>a != b</code>.

In this article we'll learn more about different types of comparisons, how JavaScript makes them, including important peculiarities.

At the end you'll find a good recipe to avoid "JavaScript quirks"-related issues.

## Boolean is the result

Like all other operators, a comparison returns a value. In this case, the value is a boolean.
All comparison operators return a boolean value:

- `true` -- means "yes", "correct" or "the truth".
- `false` -- means "no", "wrong" or "not the truth".
@@ -51,7 +57,9 @@ The algorithm to compare two strings is simple:
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 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:
In the first example above, the comparison `'Z' > 'A'` gets to a result at the first step.

The second comparison `'Glow'` and `'Glee'` needs more steps as strings are compared character-by-character:

1. `G` is the same as `G`.
2. `l` is the same as `l`.
@@ -74,7 +82,7 @@ alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1
```

For boolean values, `true` becomes `1` and `false` becomes `0`.
For boolean values, `true` becomes `1` and `false` becomes `0`.

For example:

@@ -138,11 +146,8 @@ The strict equality operator is a bit longer to write, but makes it obvious what

## Comparison with null and undefined

Let's see more edge cases.

There's a non-intuitive behavior when `null` or `undefined` are compared to other values.


For a strict equality check `===`
: These values are different, because each of them is a different type.

@@ -195,13 +200,12 @@ We get these results because:
- Comparisons `(1)` and `(2)` return `false` because `undefined` gets converted to `NaN` and `NaN` is a special numeric value which returns `false` for all comparisons.
- The equality check `(3)` returns `false` because `undefined` only equals `null`, `undefined`, and no other value.

### Evade problems

Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really. Actually, these tricky things will gradually become familiar over time, but there's a solid way to evade problems with them:
### Avoid problems

Just treat any comparison with `undefined/null` except the strict equality `===` with exceptional care.
Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really. Actually, these tricky things will gradually become familiar over time, but there's a solid way to avoid problems with them:

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.
- Treat any comparison with `undefined/null` except the strict equality `===` with exceptional care.
- Don't use comparisons `>= > < <=` with a variable which may be `null/undefined`, unless you're really sure of what you're doing. If a variable can have these values, check for them separately.

## Summary

3 changes: 1 addition & 2 deletions 1-js/02-first-steps/10-ifelse/2-check-standard/task.md
Original file line number Diff line number Diff line change
@@ -6,9 +6,8 @@ importance: 2

Using the `if..else` construct, write the code which asks: 'What is the "official" name of JavaScript?'

If the visitor enters "ECMAScript", then output "Right!", otherwise -- output: "Didn't know? ECMAScript!"
If the visitor enters "ECMAScript", then output "Right!", otherwise -- output: "You don't know? ECMAScript!"

![](ifelse_task2.svg)

[demo src="ifelse_task2"]

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@


```js
result = (a + b < 4) ? 'Below' : 'Over';
let result = (a + b < 4) ? 'Below' : 'Over';
```

5 changes: 3 additions & 2 deletions 1-js/02-first-steps/10-ifelse/5-rewrite-if-question/task.md
Original file line number Diff line number Diff line change
@@ -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';
}
```

8 changes: 4 additions & 4 deletions 1-js/02-first-steps/10-ifelse/article.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Conditional operators: if, '?'
# Conditional branching: if, '?'

Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the `if` statement and the conditional operator `?`, that's also called a "question mark" operator.

## The "if" statement

The `if` statement evaluates a condition and, if the condition's result is `true`, executes a block of code.
The `if(...)` statement evaluates a condition in parentheses and, if the result is `true`, executes a block of code.

For example:

@@ -68,7 +68,7 @@ if (cond) {

## The "else" clause

The `if` statement may contain an optional "else" block. It executes when the condition is false.
The `if` statement may contain an optional "else" block. It executes when the condition is falsy.

For example:
```js run
@@ -216,7 +216,7 @@ Depending on the condition `company == 'Netscape'`, either the first or the seco

We don't assign a result to a variable here. Instead, we execute different code depending on the condition.

**We don't recommend using the question mark operator in this way.**
**It's not recommended to use the question mark operator in this way.**

The notation is shorter than the equivalent `if` statement, which appeals to some programmers. But it is less readable.

Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@ alert( alert(1) || 2 || alert(3) );

The call to `alert` does not return a value. Or, in other words, it returns `undefined`.

1. The first OR `||` evaluates it's left operand `alert(1)`. That shows the first message with `1`.
1. The first OR `||` evaluates its left operand `alert(1)`. That shows the first message with `1`.
2. The `alert` returns `undefined`, so OR goes on to the second operand searching for a truthy value.
3. The second operand `2` is truthy, so the execution is halted, `2` is returned and then shown by the outer alert.

Original file line number Diff line number Diff line change
@@ -4,6 +4,6 @@ importance: 3

# Check the range between

Write an "if" condition to check that `age` is between `14` and `90` inclusively.
Write an `if` condition to check that `age` is between `14` and `90` inclusively.

"Inclusively" means that `age` can reach the edges `14` or `90`.
Original file line number Diff line number Diff line change
@@ -4,6 +4,6 @@ importance: 3

# Check the range outside

Write an `if` condition to check that `age` is NOT between 14 and 90 inclusively.
Write an `if` condition to check that `age` is NOT between `14` and `90` inclusively.

Create two variants: the first one using NOT `!`, the second one -- without it.
Original file line number Diff line number Diff line change
@@ -3,19 +3,19 @@
```js run demo
let userName = prompt("Who's there?", '');

if (userName == 'Admin') {
if (userName === 'Admin') {

let pass = prompt('Password?', '');

if (pass == 'TheMaster') {
if (pass === 'TheMaster') {
alert( 'Welcome!' );
} else if (pass == '' || pass == null) {
alert( 'Canceled.' );
} else if (pass === '' || pass === null) {
alert( 'Canceled' );
} else {
alert( 'Wrong password' );
}

} else if (userName == '' || userName == null) {
} else if (userName === '' || userName === null) {
alert( 'Canceled' );
} else {
alert( "I don't know you" );
Original file line number Diff line number Diff line change
@@ -6,13 +6,13 @@ 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:

66 changes: 26 additions & 40 deletions 1-js/02-first-steps/11-logical-operators/article.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Logical operators

There are three logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT).
There are four logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT), `??` (Nullish Coalescing). Here we cover the first three, the `??` operator is in the next article.

Although they are called "logical", they can be applied to values of any type, not only boolean. Their result can also be of any type.

@@ -64,7 +64,7 @@ if (hour < 10 || hour > 18 || isWeekend) {
}
```

## OR finds the first truthy value
## OR "||" finds the first truthy value [#or-finds-the-first-truthy-value]

The logic described above is somewhat classical. Now, let's bring in the "extra" features of JavaScript.

@@ -84,70 +84,57 @@ The OR `||` operator does the following:

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 truthy 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:

```js run
alert( 1 || 0 ); // 1 (1 is truthy)
alert( true || 'no matter what' ); // (true is truthy)

alert( null || 1 ); // 1 (1 is the first truthy value)
alert( null || 0 || 1 ); // 1 (the first truthy value)

alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)
```

This leads to some interesting usage compared to a "pure, classical, boolean-only OR".

1. **Getting the first truthy value from a list of variables or expressions.**

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?
For instance, we have `firstName`, `lastName` and `nickName` variables, all optional (i.e. can be undefined or have falsy values).

We can use OR `||`:
Let's use OR `||` to choose the one that has the data and show it (or `"Anonymous"` if nothing set):

```js run
let currentUser = null;
let defaultUser = "John";
let firstName = "";
let lastName = "";
let nickName = "SuperCoder";

*!*
let name = currentUser || defaultUser || "unnamed";
alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder
*/!*

alert( name ); // selects "John" – the first truthy value
```

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. This process is called "a short-circuit evaluation" because it goes as short as possible from left to right.
If all variables were falsy, `"Anonymous"` would show up.

This is clearly seen when the expression given as the second argument has a side effect like a variable assignment.
2. **Short-circuit evaluation.**

In the example below, `x` does not get assigned:
Another feature of OR `||` operator is the so-called "short-circuit" evaluation.

```js run no-beautify
let x;
It means that `||` processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.

*!*true*/!* || (x = 1);
The importance of this feature becomes obvious if an operand isn't just a value, but an expression with a side effect, such as a variable assignment or a function call.
alert(x); // undefined, because (x = 1) not evaluated
```

If, instead, the first argument is `false`, `||` evaluates the second one, thus running the assignment:
In the example below, only the second message is printed:
```js run no-beautify
let x;
*!*false*/!* || (x = 1);
alert(x); // 1
*!*true*/!* || alert("not printed");
*!*false*/!* || alert("printed");
```
An assignment is a simple case. There may be side effects, that won't show up if the evaluation doesn't reach them.
In the first line, the OR `||` operator stops the evaluation immediately upon seeing `true`, so the `alert` isn't run.

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 this can be handy.
Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.

## && (AND)

@@ -186,7 +173,7 @@ if (1 && 0) { // evaluated as true && false
```


## AND finds the first falsy value
## AND "&&" finds the first falsy value

Given multiple AND'ed values:
@@ -236,7 +223,8 @@ The precedence of AND `&&` operator is higher than OR `||`.
So the code `a && b || c && d` is essentially the same as if the `&&` expressions were in parentheses: `(a && b) || (c && d)`.
````
Just like OR, the AND `&&` operator can sometimes replace `if`.
````warn header="Don't replace `if` with `||` or `&&`"
Sometimes, people use the AND `&&` operator as a "shorter way to write `if`".
For instance:
@@ -253,14 +241,12 @@ So we basically have an analogue for:
```js run
let x = 1;
if (x > 0) {
alert( 'Greater than zero!' );
}
if (x > 0) alert( 'Greater than zero!' );
```
The variant with `&&` appears shorter. But `if` is more obvious and tends to be a little bit more readable.
Although, the variant with `&&` appears shorter, `if` is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use `if` if we want `if` and use `&&` if we want AND.
````
So we recommend using every construct for its purpose: use `if` if we want if and use `&&` if we want AND.
## ! (NOT)
169 changes: 169 additions & 0 deletions 1-js/02-first-steps/12-nullish-coalescing-operator/article.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
# Nullish coalescing operator '??'

[recent browser="new"]

The nullish coalescing operator is written as two question marks `??`.

As it treats `null` and `undefined` similarly, we'll use a special term here, in this article. We'll say that an expression is "defined" when it's neither `null` nor `undefined`.

The result of `a ?? b` is:
- if `a` is defined, then `a`,
- if `a` isn't defined, then `b`.

In other words, `??` returns the first argument if it's not `null/undefined`. Otherwise, the second one.

The nullish coalescing operator isn't anything completely new. It's just a nice syntax to get the first "defined" value of the two.

We can rewrite `result = a ?? b` using the operators that we already know, like this:

```js
result = (a !== null && a !== undefined) ? a : b;
```

Now it should be absolutely clear what `??` does. Let's see where it helps.

The common use case for `??` is to provide a default value for a potentially undefined variable.

For example, here we show `user` if defined, otherwise `Anonymous`:

```js run
let user;

alert(user ?? "Anonymous"); // Anonymous (user not defined)
```
Here's the example with `user` assigned to a name:
```js run
let user = "John";

alert(user ?? "Anonymous"); // John (user defined)
```
We can also use a sequence of `??` to select the first value from a list that isn't `null/undefined`.
Let's say we have a user's data in variables `firstName`, `lastName` or `nickName`. All of them may be not defined, if the user decided not to enter a value.
We'd like to display the user name using one of these variables, or show "Anonymous" if all of them aren't defined.
Let's use the `??` operator for that:
```js run
let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// shows the first defined value:
*!*
alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder
*/!*
```
## Comparison with ||
The OR `||` operator can be used in the same way as `??`, as it was described in the [previous chapter](info:logical-operators#or-finds-the-first-truthy-value).
For example, in the code above we could replace `??` with `||` and still get the same result:
```js run
let firstName = null;
let lastName = null;
let nickName = "Supercoder";

// shows the first truthy value:
*!*
alert(firstName || lastName || nickName || "Anonymous"); // Supercoder
*/!*
```
Historically, the OR `||` operator was there first. It exists since the beginning of JavaScript, so developers were using it for such purposes for a long time.
On the other hand, the nullish coalescing operator `??` was added to JavaScript only recently, and the reason for that was that people weren't quite happy with `||`.
The important difference between them is that:
- `||` returns the first *truthy* value.
- `??` returns the first *defined* value.
In other words, `||` doesn't distinguish between `false`, `0`, an empty string `""` and `null/undefined`. They are all the same -- falsy values. If any of these is the first argument of `||`, then we'll get the second argument as the result.
In practice though, we may want to use default value only when the variable is `null/undefined`. That is, when the value is really unknown/not set.
For example, consider this:
```js run
let height = 0;

alert(height || 100); // 100
alert(height ?? 100); // 0
```
- The `height || 100` checks `height` for being a falsy value, and it's `0`, falsy indeed.
- so the result of `||` is the second argument, `100`.
- The `height ?? 100` checks `height` for being `null/undefined`, and it's not,
- so the result is `height` "as is", that is `0`.
In practice, the zero height is often a valid value, that shouldn't be replaced with the default. So `??` does just the right thing.
## Precedence
The precedence of the `??` operator is about the same as `||`, just a bit lower. It equals `5` in the [MDN table](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table), while `||` is `6`.
That means that, just like `||`, the nullish coalescing operator `??` is evaluated before `=` and `?`, but after most other operations, such as `+`, `*`.
So if we'd like to choose a value with `??` in an expression with other operators, consider adding parentheses:
```js run
let height = null;
let width = null;

// important: use parentheses
let area = (height ?? 100) * (width ?? 50);

alert(area); // 5000
```
Otherwise, if we omit parentheses, then as `*` has the higher precedence than `??`, it would execute first, leading to incorrect results.
```js
// without parentheses
let area = height ?? 100 * width ?? 50;

// ...works the same as this (probably not what we want):
let area = height ?? (100 * width) ?? 50;
```
### Using ?? with && or ||
Due to safety reasons, JavaScript forbids using `??` together with `&&` and `||` operators, unless the precedence is explicitly specified with parentheses.
The code below triggers a syntax error:
```js run
let x = 1 && 2 ?? 3; // Syntax error
```
The limitation is surely debatable, it was added to the language specification with the purpose to avoid programming mistakes, when people start to switch from `||` to `??`.
Use explicit parentheses to work around it:
```js run
*!*
let x = (1 && 2) ?? 3; // Works
*/!*

alert(x); // 2
```
## Summary
- The nullish coalescing operator `??` provides a short way to choose the first "defined" value from a list.
It's used to assign default values to variables:
```js
// set height=100, if height is null or undefined
height = height ?? 100;
```
- The operator `??` has a very low precedence, only a bit higher than `?` and `=`, so consider adding parentheses when using it in an expression.
- It's forbidden to use it with `||` or `&&` without explicit parentheses.
Original file line number Diff line number Diff line change
@@ -10,6 +10,6 @@ do {
The loop `do..while` repeats while both checks are truthy:

1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`.
2. The check `&& num` is false when `num` is `null` or a empty string. Then the `while` loop stops too.
2. The check `&& num` is false when `num` is `null` or an empty string. Then the `while` loop stops too.

P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required.
Original file line number Diff line number Diff line change
@@ -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 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.
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.
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@ while (condition) {
}
```

While the `condition` is `true`, the `code` from the loop body is executed.
While the `condition` is truthy, the `code` from the loop body is executed.

For instance, the loop below outputs `i` while `i < 3`:

@@ -84,7 +84,7 @@ This form of syntax should only be used when you want the body of the loop to ex

## The "for" loop

The `for` loop is the most commonly used loop.
The `for` loop is more complex, but it's also the most commonly used loop.

It looks like this:

@@ -106,13 +106,13 @@ Let's examine the `for` statement part-by-part:

| part | | |
|-------|----------|----------------------------------------------------------------------------|
| begin | `i = 0` | Executes once upon entering the loop. |
| begin | `let i = 0` | Executes once upon entering the loop. |
| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. |
| step| `i++` | Executes after the body on each iteration but before the condition check. |
| body | `alert(i)`| Runs again and again while the condition is truthy. |

| step| `i++` | Executes after the body on each iteration. |

The general loop algorithm works like this:

```
Run begin
→ (if condition → run body and run step)
@@ -121,6 +121,8 @@ Run begin
→ ...
```

That is, `begin` executes once, and then it iterates: after each `condition` test, `body` and `step` are executed.

If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.

Here's exactly what happens in our case:
@@ -210,7 +212,7 @@ But we can force the exit at any time using the special `break` directive.

For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered:

```js
```js run
let sum = 0;

while (true) {
@@ -254,7 +256,7 @@ For even values of `i`, the `continue` directive stops executing the body and pa
````smart header="The `continue` directive helps decrease nesting"
A loop that shows odd values could look like this:

```js
```js run
for (let i = 0; i < 10; i++) {

if (i % 2) {
@@ -266,7 +268,7 @@ for (let i = 0; i < 10; i++) {

From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an `if` block instead of using `continue`.

But as a side-effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of`if` is longer than a few lines, that may decrease the overall readability.
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 '?'"
@@ -289,8 +291,7 @@ if (i > 5) {
(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here
```
...it stops working. Code like this will give a syntax error:
...it stops working: there's a syntax error.
This is just another reason not to use the question mark operator `?` instead of `if`.
````
@@ -299,7 +300,7 @@ This is just another reason not to use the question mark operator `?` instead of

Sometimes we need to break out from multiple nested loops at once.

For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(3,3)`:
For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(2,2)`:

```js run no-beautify
for (let i = 0; i < 3; i++) {
@@ -308,8 +309,7 @@ for (let i = 0; i < 3; i++) {

let input = prompt(`Value at coords (${i},${j})`, '');

// what if I want to exit from here to Done (below)?

// what if we want to exit from here to Done (below)?
}
}

@@ -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
@@ -358,17 +358,28 @@ for (let i = 0; i < 3; i++) { ... }

The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop.

````warn header="Labels are not a \"goto\""
````warn header="Labels do not allow to \"jump\" anywhere"
Labels do not allow us to jump into an arbitrary place in the code.
For example, it is impossible to do this:
```js
break label; // jumps to label? No.
break label; // jump to the label below (doesn't work)
label: for (...)
```
A call to `break/continue` is only possible from inside a loop and the label must be somewhere above the directive.
A `break` directive must be inside a code block. Technically, any labelled code block will do, e.g.:
```js
label: {
// ...
break label; // works
// ...
}
```
...Although, 99.9% of the time `break` is used inside loops, as we've seen in the examples above.
A `continue` is only possible from inside a loop.
````

## Summary
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -47,7 +47,7 @@ switch (a) {
break;
*/!*
case 5:
alert( 'Too large' );
alert( 'Too big' );
break;
default:
alert( "I don't know such values" );
@@ -117,15 +117,15 @@ Several variants of `case` which share the same code can be grouped.
For example, if we want the same code to run for `case 3` and `case 5`:
```js run no-beautify
let a = 2 + 2;
let a = 3;
switch (a) {
case 4:
alert('Right!');
break;
*!*
case 3: // (*) grouped two cases
case 3: // (*) grouped two cases
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
Original file line number Diff line number Diff line change
@@ -14,4 +14,4 @@ function checkAge(age) {
}
```

Note that the parentheses around `age > 18` are not required here. They exist for better readabilty.
Note that the parentheses around `age > 18` are not required here. They exist for better readability.
Original file line number Diff line number Diff line change
@@ -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?');
}
}
```
Original file line number Diff line number Diff line change
@@ -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) );
}
```

Original file line number Diff line number Diff line change
@@ -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, we'll see examples later) and finally the code of the function, also named "the function body", between curly braces.

![](function_basics.png)
```js
function name(parameter1, parameter2, ... parameterN) {
...body...
}
```

Our new function can be called by its name: `showMessage()`.

@@ -133,26 +137,23 @@ It's a good practice to minimize the use of global variables. Modern code has fe

## Parameters

We can pass arbitrary data to functions using parameters (also called *function arguments*) .
We can pass arbitrary data to functions using parameters.

In the example below, the function has two parameters: `from` and `text`.

```js run
function showMessage(*!*from, text*/!*) { // arguments: from, text
function showMessage(*!*from, text*/!*) { // parameters: from, text
alert(from + ': ' + text);
}

*!*
showMessage('Ann', 'Hello!'); // Ann: Hello! (*)
showMessage('Ann', "What's up?"); // Ann: What's up? (**)
*/!*
*!*showMessage('Ann', 'Hello!');*/!* // Ann: Hello! (*)
*!*showMessage('Ann', "What's up?");*/!* // Ann: What's up? (**)
```
When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them.
Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value:

```js run
function showMessage(from, text) {

@@ -171,19 +172,31 @@ showMessage(from, "Hello"); // *Ann*: Hello
alert( from ); // Ann
```
When a value is passed as a function parameter, it's also called an *argument*.
In other words, to put these terms straight:
- A parameter is the variable listed inside the parentheses in the function declaration (it's a declaration time term)
- An argument is the value that is passed to the function when it is called (it's a call time term).
We declare functions listing their parameters, then call them passing arguments.
In the example above, one might say: "the function `showMessage` is declared with two parameters, then called with two arguments: `from` and `"Hello"`".
## Default values
If a parameter is not provided, then its value becomes `undefined`.
If a function is called, but an argument is not provided, then the corresponding value becomes `undefined`.
For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument:
```js
showMessage("Ann");
```
That's not an error. Such a call would output `"Ann: undefined"`. There's no `text`, so it's assumed that `text === undefined`.
That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`.
If we want to use a "default" `text` in this case, then we can specify it after `=`:
We can specify the so-called "default" (to use if omitted) value for a parameter in the function declaration, using `=`:
```js run
function showMessage(from, *!*text = "no text given"*/!*) {
@@ -205,42 +218,57 @@ function showMessage(from, text = anotherFunction()) {
```
```smart header="Evaluation of default parameters"
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.

In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter. This is in contrast to some other languages like Python, where any default parameters are evaluated only once during the initial interpretation.
In the example above, `anotherFunction()` isn't called at all, if the `text` parameter is provided.

On the other hand, it's independently called every time when `text` is missing.
```

### Alternative default parameters

````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.
Sometimes it makes sense to assign default values for parameters not in the function declaration, but at a later stage.

For instance, an explicit check for being `undefined`:
We can check if the parameter is passed during the function execution, by comparing it with `undefined`:

```js run
function showMessage(text) {
// ...

```js
function showMessage(from, text) {
*!*
if (text === undefined) {
text = 'no text given';
if (text === undefined) { // if the parameter is missing
text = 'empty message';
}
*/!*

alert( from + ": " + text );
alert(text);
}

showMessage(); // empty message
```
...Or the `||` operator:
...Or we could use the `||` operator:
```js
function showMessage(from, text) {
// if text is falsy then text gets the "default" value
text = text || 'no text given';
function showMessage(text) {
// if text is undefined or otherwise falsy, set it to 'empty'
text = text || 'empty';
...
}
```
Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when most falsy values, such as `0`, should be considered "normal":
````
```js run
function showCount(count) {
// if count is undefined or null, show "unknown"
alert(count ?? "unknown");
}

showCount(0); // 0
showCount(null); // unknown
showCount(); // unknown
```
## Returning a value
@@ -263,7 +291,7 @@ 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;
*/!*
@@ -335,7 +363,19 @@ That doesn't work, because JavaScript assumes a semicolon after `return`. That'l
return*!*;*/!*
(some + long + expression + or + whatever * f(a) + f(b))
```
So, it effectively becomes an empty return. We should put the value on the same line instead.
So, it effectively becomes an empty return.
If we want the returned expression to wrap across multiple lines, we should start it at the same line as `return`. Or at least put the opening parentheses there as follows:
```js
return (
some + long + expression
+ or +
whatever * f(a) + f(b)
)
```
And it will work just as we expect it to.
````
## Naming a function [#function-naming]
@@ -384,7 +424,7 @@ Functions that are used *very often* sometimes have ultrashort names.

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 and descriptive.
These are exceptions. Generally function names should be concise and descriptive.
```

## Functions == Comments
Loading