Skip to content

Sync with upstream @ 8558fa8f #28

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 130 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
130 commits
Select commit Hold shift + click to select a range
f723253
transpiler def
joaquinelio Mar 28, 2021
7d624ef
typo it's
joaquinelio Apr 18, 2021
47b1ca8
Fix grammar and wrong information
Violet-Bora-Lee Apr 21, 2021
0ad314c
fix grammar
Violet-Bora-Lee Apr 22, 2021
62bc619
insert empty line
Violet-Bora-Lee Apr 22, 2021
8292f9c
Update article.md
JackStaples Apr 24, 2021
07b364d
Replace preposition with verb
mikemitchell574 Apr 29, 2021
981e34b
Update article.md
josecervino Apr 30, 2021
252cccf
always strict
joaquinelio May 7, 2021
5f972c8
fix(classes): replace [[FunctionKind]] with [[IsClassConstructor]]
H2rmone May 11, 2021
243a0b1
Merge pull request #2582 from joaquinelio/patch-4
iliakan May 13, 2021
055cab1
Merge pull request #2585 from Violet-Bora-Lee/patch-1
iliakan May 13, 2021
c78b2c9
Merge pull request #2586 from Violet-Bora-Lee/patch-2
iliakan May 13, 2021
10c3bcf
Merge pull request #2588 from Violet-Bora-Lee/patch-3
iliakan May 13, 2021
4f06415
closes #2583
iliakan May 13, 2021
74d14af
minor fixes
iliakan May 13, 2021
57e7d67
Merge pull request #2592 from JackStaples/patch-2
iliakan May 13, 2021
5e9db70
Merge pull request #2593 from mikemitchell574/master
iliakan May 13, 2021
0cbf55d
Merge pull request #2595 from josecervino/patch-1
iliakan May 13, 2021
094b829
Merge pull request #2598 from joaquinelio/patch-7
iliakan May 13, 2021
339535d
Merge pull request #2599 from H2rmone/master
iliakan May 13, 2021
3bf8830
Update article.md
iliakan May 13, 2021
237920b
Update article.md
iliakan May 13, 2021
33f1b11
minor fixes
iliakan May 13, 2021
6ad8930
minor fixes
iliakan May 13, 2021
fafab82
typo
joaquinelio May 15, 2021
4177be3
Merge pull request #2602 from joaquinelio/patch-4
iliakan May 16, 2021
80956ed
closes #2600
iliakan May 16, 2021
11e0890
Fix typo.
odsantos May 16, 2021
89183a0
minor fixes
iliakan May 16, 2021
bad5236
minor fixes
iliakan May 16, 2021
70049c3
minor fixes
iliakan May 16, 2021
859fa9b
minor fixes
iliakan May 16, 2021
fb09afc
minor fixes
iliakan May 16, 2021
f598b72
minor fixes
iliakan May 16, 2021
f841402
minor fixes
iliakan May 16, 2021
18a0394
minor fixes
iliakan May 16, 2021
ac96ede
Remove mentions of :host-context
web-padawan May 17, 2021
ae8248b
minor fixes
iliakan May 17, 2021
d2ae45d
Update article.md
Dorin-David May 20, 2021
ffa79a8
minor fixes
iliakan May 24, 2021
a917f9c
minor fixes
iliakan May 24, 2021
94837c2
minor fixes
iliakan May 24, 2021
3e74537
minor fixes
iliakan May 24, 2021
006343a
minor fixes
iliakan May 24, 2021
df45aed
minor fixes
iliakan May 24, 2021
8871521
minor fixes
iliakan May 24, 2021
1770074
minor fixes
iliakan May 24, 2021
3dbe9d1
minor fixes
iliakan May 24, 2021
2fc7cb2
minor fixes
iliakan May 24, 2021
649a159
minor fixes
iliakan May 24, 2021
62db4bb
minor fixes
iliakan May 24, 2021
3288801
minor fixes
iliakan May 24, 2021
6db4961
minor fixes
iliakan May 24, 2021
4343545
minor fixes
iliakan May 24, 2021
053cc05
minor fixes
iliakan May 24, 2021
842f0e2
minor fixes
iliakan May 24, 2021
70bb265
minor fixes
iliakan May 24, 2021
fc3c071
minor fixes
iliakan May 24, 2021
7a30a00
minor fixes
iliakan May 24, 2021
6cfa8b4
minor fixes
iliakan May 24, 2021
649c758
minor fixes
iliakan May 24, 2021
f2636ee
minor fixes
iliakan May 24, 2021
9ba208f
minor fixes
iliakan May 24, 2021
cf33b67
minor fixes
iliakan May 24, 2021
f8313dc
Update article.md
AhmedElaguab May 28, 2021
88ba2c2
Merge pull request #2 from AhmedElaguab/AhmedElaguab-fix-typo
AhmedElaguab May 28, 2021
4c35f59
"not required" vs "incorrect"
joaquinelio May 29, 2021
c2d5f8e
easier to read
joaquinelio Jun 4, 2021
52cb884
Update article.md
leviding Jun 7, 2021
6a742c4
Update article.md
leviding Jun 8, 2021
581802d
minor fixes
iliakan Jun 9, 2021
68172cc
typo
joaquinelio Jun 10, 2021
0e49461
typpo
joaquinelio Jun 10, 2021
964ba15
function parameters vs arguments
iliakan Jun 13, 2021
1ccd673
Merge pull request #2624 from joaquinelio/patch-11
iliakan Jun 13, 2021
54ff266
Merge pull request #2623 from joaquinelio/patch-9
iliakan Jun 13, 2021
2b1600e
Merge pull request #2622 from leviding/patch-37
iliakan Jun 13, 2021
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
9eebc0d
merging all conflicts
iliakan Jun 21, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions 1-js/01-getting-started/1-intro/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,15 @@ Prohlížeč má zabudovaný engine, který se někdy nazývá „virtuální st

Různé enginy mají různá „kódová označení“. Například:

<<<<<<< HEAD
- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- v Chrome a Opeře.
- [SpiderMonkey](https://cs.wikipedia.org/wiki/SpiderMonkey) -- ve Firefoxu.
- Existují i jiná krycí jména, například „Chakra“ pro Internet Explorer, „ChakraCore“ pro Microsoft Edge, „Nitro“ a „SquirrelFish“ pro Safari, a tak dále.
=======
- [V8](https://en.wikipedia.org/wiki/V8_(JavaScript_engine)) -- in Chrome and Opera.
- [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) -- in Firefox.
- ...There are other codenames like "Chakra" for IE, "JavaScriptCore", "Nitro" and "SquirrelFish" for Safari, etc.
>>>>>>> 8558fa8f5cfb16ef62aa537d323e34d9bef6b4de

Výše uvedené pojmy je dobré si pamatovat, protože se používají ve vývojářských článcích na internetu. Budeme je používat i my. Například „vlastnost X je podporována ve V8“ znamená, že pravděpodobně bude fungovat v Chrome a Opeře.

Expand Down
36 changes: 16 additions & 20 deletions 1-js/02-first-steps/02-structure/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.**

Expand All @@ -56,40 +56,36 @@ 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.
Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/05-types/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ 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>.

## BigInt
## 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.

Expand Down
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/08-operators/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ 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 ** 2 ); // 2² = 4
alert( 2 ** 3 ); // 2³ = 8
alert( 2 ** 4 ); // 2⁴ = 16
```

Expand Down
51 changes: 32 additions & 19 deletions 1-js/02-first-steps/15-function-basics/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ function showMessage() {
}
```

The `function` keyword goes first, then goes the *name of the function*, then a list of *parameters* between the parentheses (comma-separated, empty in the example above) 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.

```js
function name(parameters) {
function name(parameter1, parameter2, ... parameterN) {
...body...
}
```
Expand Down Expand Up @@ -137,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) {

Expand All @@ -175,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 `sayMessage` 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"*/!*) {
Expand All @@ -211,19 +220,23 @@ function showMessage(from, text = anotherFunction()) {
```smart header="Evaluation of default parameters"
In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.

In the example above, `anotherFunction()` is called every time `showMessage()` is called without the `text` parameter.
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

Sometimes it makes sense to set default values for parameters not in the function declaration, but at a later stage, during its execution.
Sometimes it makes sense to assign default values for parameters not in the function declaration, but at a later stage.

To check for an omitted parameter, we can compare it with `undefined`:
We can check if the parameter is passed during the function execution, by comparing it with `undefined`:

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

*!*
if (text === undefined) {
if (text === undefined) { // if the parameter is missing
text = 'empty message';
}
*/!*
Expand All @@ -237,18 +250,18 @@ showMessage(); // empty message
...Or we could use the `||` operator:

```js
// if text parameter is omitted or "" is passed, set it to 'empty'
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 falsy values, such as `0`, are considered regular:
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
// if there's no "count" parameter, show "unknown"
function showCount(count) {
// if count is undefined or null, show "unknown"
alert(count ?? "unknown");
}

Expand Down
2 changes: 1 addition & 1 deletion 1-js/03-code-quality/01-debugging-chrome/article.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Debugging in Chrome
# Debugging in the browser

Before writing more complex code, let's talk about debugging.

Expand Down
2 changes: 1 addition & 1 deletion 1-js/03-code-quality/06-polyfills/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Here, in this chapter, our purpose is to get the gist of how they work, and thei

## Transpilers

A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a special piece of software that can parse ("read and understand") modern code, and rewrite it using older syntax constructs, so that the result would be the same.
A [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler) is a special piece of software that translates source code to another source code. It can parse ("read and understand") modern code and rewrite it using older syntax constructs, so that it'll also work in outdated engines.

E.g. JavaScript before year 2020 didn't have the "nullish coalescing operator" `??`. So, if a visitor uses an outdated browser, it may fail to understand the code like `height = height ?? 100`.

Expand Down
9 changes: 5 additions & 4 deletions 1-js/04-object-basics/06-constructor-new/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,14 @@ Now if we want to create other users, we can call `new User("Ann")`, `new User("

That's the main purpose of constructors -- to implement reusable object creation code.

Let's note once again -- technically, any function can be used as a constructor. That is: any function can be run with `new`, and it will execute the algorithm above. The "capital letter first" is a common agreement, to make it clear that a function is to be run with `new`.
Let's note once again -- technically, any function (except arrow functions, as they don't have `this`) can be used as a constructor. It can be run with `new`, and it will execute the algorithm above. The "capital letter first" is a common agreement, to make it clear that a function is to be run with `new`.

````smart header="new function() { ... }"
If we have many lines of code all about creation of a single complex object, we can wrap them in constructor function, like this:
If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:

```js
let user = new function() {
// create a function and immediately call it with new
let user = new function() {
this.name = "John";
this.isAdmin = false;

Expand All @@ -80,7 +81,7 @@ let user = new function() {
};
```

The constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
This constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
````

## Constructor mode test: new.target
Expand Down
48 changes: 35 additions & 13 deletions 1-js/04-object-basics/09-object-toprimitive/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,36 @@

What happens when objects are added `obj1 + obj2`, subtracted `obj1 - obj2` or printed using `alert(obj)`?

In that case, objects are auto-converted to primitives, and then the operation is carried out.
JavaScript doesn't exactly allow to customize how operators work on objects. Unlike some other programming languages, such as Ruby or C++, we can't implement a special object method to handle an addition (or other operators).

In case of such operations, objects are auto-converted to primitives, and then the operation is carried out over these primitives and results in a primitive value.

That's an important limitation, as the result of `obj1 + obj2` can't be another object!

E.g. we can't make objects representing vectors or matrices (or achievements or whatever), add them and expect a "summed" object as the result. Such architectural feats are automatically "off the board".

So, because we can't do much here, there's no maths with objects in real projects. When it happens, it's usually because of a coding mistake.

In this chapter we'll cover how an object converts to primitive and how to customize it.

We have two purposes:

1. It will allow us to understand what's going on in case of coding mistakes, when such an operation happened accidentally.
2. There are exceptions, where such operations are possible and look good. E.g. subtracting or comparing dates (`Date` objects). We'll come across them later.

## Conversion rules

In the chapter <info:type-conversions> we've seen the rules for numeric, string and boolean conversions of primitives. But we left a gap for objects. Now, as we know about methods and symbols it becomes possible to fill it.

1. All objects are `true` in a boolean context. There are only numeric and string conversions.
2. The numeric conversion happens when we subtract objects or apply mathematical functions. For instance, `Date` objects (to be covered in the chapter <info:date>) can be subtracted, and the result of `date1 - date2` is the time difference between two dates.
3. As for the string conversion -- it usually happens when we output an object like `alert(obj)` and in similar contexts.

## ToPrimitive

We can fine-tune string and numeric conversion, using special object methods.

There are three variants of type conversion, so-called "hints", described in the [specification](https://tc39.github.io/ecma262/#sec-toprimitive):
There are three variants of type conversion, that happen in various situations.

They're called "hints", as described in the [specification](https://tc39.github.io/ecma262/#sec-toprimitive):

`"string"`
: For an object-to-string conversion, when we're doing an operation on an object that expects a string, like `alert`:
Expand Down Expand Up @@ -82,11 +99,14 @@ Let's start from the first method. There's a built-in symbol named `Symbol.toPri

```js
obj[Symbol.toPrimitive] = function(hint) {
// must return a primitive value
// here goes the code to convert this object to a primitive
// it must return a primitive value
// hint = one of "string", "number", "default"
};
```

If the method `Symbol.toPrimitive` exists, it's used for all hints, and no more methods are needed.

For instance, here `user` object implements it:

```js run
Expand All @@ -111,12 +131,12 @@ As we can see from the code, `user` becomes a self-descriptive string or a money

## toString/valueOf

Methods `toString` and `valueOf` come from ancient times. They are not symbols (symbols did not exist that long ago), but rather "regular" string-named methods. They provide an alternative "old-style" way to implement the conversion.
If there's no `Symbol.toPrimitive` then JavaScript tries to find methods `toString` and `valueOf`:

If there's no `Symbol.toPrimitive` then JavaScript tries to find them and try in the order:
- For the "string" hint: `toString`, and if it doesn't exist, then `valueOf` (so `toString` has the priority for string conversions).
- For other hints: `valueOf`, and if it doesn't exist, then `toString` (so `valueOf` has the priority for maths).

- `toString -> valueOf` for "string" hint.
- `valueOf -> toString` otherwise.
Methods `toString` and `valueOf` come from ancient times. They are not symbols (symbols did not exist that long ago), but rather "regular" string-named methods. They provide an alternative "old-style" way to implement the conversion.

These methods must return a primitive value. If `toString` or `valueOf` returns an object, then it's ignored (same as if there were no method).

Expand All @@ -136,9 +156,9 @@ alert(user.valueOf() === user); // true

So if we try to use an object as a string, like in an `alert` or so, then by default we see `[object Object]`.

And the default `valueOf` is mentioned here only for the sake of completeness, to avoid any confusion. As you can see, it returns the object itself, and so is ignored. Don't ask me why, that's for historical reasons. So we can assume it doesn't exist.
The default `valueOf` is mentioned here only for the sake of completeness, to avoid any confusion. As you can see, it returns the object itself, and so is ignored. Don't ask me why, that's for historical reasons. So we can assume it doesn't exist.

Let's implement these methods.
Let's implement these methods to customize the conversion.

For instance, here `user` does the same as above using a combination of `toString` and `valueOf` instead of `Symbol.toPrimitive`:

Expand Down Expand Up @@ -183,7 +203,7 @@ alert(user + 500); // toString -> John500

In the absence of `Symbol.toPrimitive` and `valueOf`, `toString` will handle all primitive conversions.

## Return types
### A conversion can return any primitive type

The important thing to know about all primitive-conversion methods is that they do not necessarily return the "hinted" primitive.

Expand Down Expand Up @@ -252,4 +272,6 @@ The conversion algorithm is:
3. Otherwise if hint is `"number"` or `"default"`
- try `obj.valueOf()` and `obj.toString()`, whatever exists.

In practice, it's often enough to implement only `obj.toString()` as a "catch-all" method for all conversions that return a "human-readable" representation of an object, for logging or debugging purposes.
In practice, it's often enough to implement only `obj.toString()` as a "catch-all" method for string conversions that should return a "human-readable" representation of an object, for logging or debugging purposes.

As for math operations, JavaScript doesn't provide a way to "override" them using methods, so real life projects rarely use them on objects.
Loading