Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
117 commits
Select commit Hold shift + click to select a range
f723253
transpiler def
joaquinelio Mar 28, 2021
3d88d33
Update article.md
ZYinMD Jun 13, 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
d18f6e3
merging all conflicts
iliakan Aug 30, 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
4 changes: 4 additions & 0 deletions 1-js/02-first-steps/04-variables/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ Endi `=` tayinlash operatori yordamida unga ba'zi ma'lumotlarni kiritishimiz mum
let message;

*!*
<<<<<<< HEAD
message = 'Hello'; // matni saqlash
=======
message = 'Hello'; // store the string 'Hello' in the variable named message
>>>>>>> 4d01fc20d4d82358e61518a31efe80dec9bb2602
*/!*
```

Expand Down
6 changes: 5 additions & 1 deletion 1-js/02-first-steps/13-while-for/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ Keling, `for` ifodani qisma ko'rib chiqamiz:

| qism | | |
|-------|----------|----------------------------------------------------------------------------|
<<<<<<< HEAD
<<<<<<< HEAD:1-js/02-first-steps/12-while-for/article.md
| boshlanishi | `i = 0` | Tsikldan e'lon qilingandan keyin bir marta bajariladi. |
| shart | `i < 3`| Har bir tsikl takrorlashdan oldin tekshiriladi. Agar yolg'on bo'lsa, tsikl to'xtaydi. |
Expand All @@ -129,6 +130,9 @@ Keling, `for` ifodani qisma ko'rib chiqamiz:
Umumiy tsikl algoritmi quyidagicha ishlaydi:
=======
| begin | `i = 0` | Executes once upon entering the loop. |
=======
| begin | `let i = 0` | Executes once upon entering the loop. |
>>>>>>> 4d01fc20d4d82358e61518a31efe80dec9bb2602
| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. |
| body | `alert(i)`| Runs again and again while the condition is truthy. |
| step| `i++` | Executes after the body on each iteration. |
Expand Down Expand Up @@ -438,7 +442,7 @@ label: {
}
```

...Although, 99.9% of the time `break` used is inside loops, as we've seen in the examples above.
...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.
>>>>>>> fb4fc33a2234445808100ddc9f5e4dcec8b3d24c:1-js/02-first-steps/13-while-for/article.md
Expand Down
6 changes: 5 additions & 1 deletion 1-js/02-first-steps/15-function-basics/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ In other words, to put these terms straight:

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"`".
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
Expand Down Expand Up @@ -304,6 +304,7 @@ function showMessage(text) {
showMessage(); // empty message
```

<<<<<<< HEAD
<<<<<<< HEAD:1-js/02-first-steps/14-function-basics/article.md
...Yoki `||` operatori:

Expand All @@ -313,6 +314,9 @@ function showMessage(from, text) {
text = text || 'matn berilmagan';
=======
...Or we could use the `??` operator:
=======
...Or we could use the `||` operator:
>>>>>>> 4d01fc20d4d82358e61518a31efe80dec9bb2602

```js
function showMessage(text) {
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 @@ -53,7 +53,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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ importance: 2

# Ikki funktsiya - bitta obyekt

<<<<<<< HEAD
`A` va `B` funktsiyalarini `new A()==new B()` kabi yaratish mumkinmi?
=======
Is it possible to create functions `A` and `B` so that `new A() == new B()`?
>>>>>>> 4d01fc20d4d82358e61518a31efe80dec9bb2602

```js no-beautify
function A() { ... }
Expand Down
277 changes: 277 additions & 0 deletions 1-js/04-object-basics/09-object-toprimitive/article.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@

# Object to primitive conversion

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

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.

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

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

```js
// output
alert(obj);

// using object as a property key
anotherObj[obj] = 123;
```

`"number"`
: For an object-to-number conversion, like when we're doing maths:

```js
// explicit conversion
let num = Number(obj);

// maths (except binary plus)
let n = +obj; // unary plus
let delta = date1 - date2;

// less/greater comparison
let greater = user1 > user2;
```

`"default"`
: Occurs in rare cases when the operator is "not sure" what type to expect.

For instance, binary plus `+` can work both with strings (concatenates them) and numbers (adds them), so both strings and numbers would do. So if a binary plus gets an object as an argument, it uses the `"default"` hint to convert it.

Also, if an object is compared using `==` with a string, number or a symbol, it's also unclear which conversion should be done, so the `"default"` hint is used.

```js
// binary plus uses the "default" hint
let total = obj1 + obj2;

// obj == number uses the "default" hint
if (user == 1) { ... };
```

The greater and less comparison operators, such as `<` `>`, can work with both strings and numbers too. Still, they use the `"number"` hint, not `"default"`. That's for historical reasons.

In practice though, we don't need to remember these peculiar details, because all built-in objects except for one case (`Date` object, we'll learn it later) implement `"default"` conversion the same way as `"number"`. And we can do the same.

```smart header="No `\"boolean\"` hint"
Please note -- there are only three hints. It's that simple.

There is no "boolean" hint (all objects are `true` in boolean context) or anything else. And if we treat `"default"` and `"number"` the same, like most built-ins do, then there are only two conversions.
```

**To do the conversion, JavaScript tries to find and call three object methods:**

1. Call `obj[Symbol.toPrimitive](hint)` - the method with the symbolic key `Symbol.toPrimitive` (system symbol), if such method exists,
2. Otherwise if hint is `"string"`
- try `obj.toString()` and `obj.valueOf()`, whatever exists.
3. Otherwise if hint is `"number"` or `"default"`
- try `obj.valueOf()` and `obj.toString()`, whatever exists.

## Symbol.toPrimitive

Let's start from the first method. There's a built-in symbol named `Symbol.toPrimitive` that should be used to name the conversion method, like this:

```js
obj[Symbol.toPrimitive] = function(hint) {
// 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
let user = {
name: "John",
money: 1000,

[Symbol.toPrimitive](hint) {
alert(`hint: ${hint}`);
return hint == "string" ? `{name: "${this.name}"}` : this.money;
}
};

// conversions demo:
alert(user); // hint: string -> {name: "John"}
alert(+user); // hint: number -> 1000
alert(user + 500); // hint: default -> 1500
```

As we can see from the code, `user` becomes a self-descriptive string or a money amount depending on the conversion. The single method `user[Symbol.toPrimitive]` handles all conversion cases.


## toString/valueOf

If there's no `Symbol.toPrimitive` then JavaScript tries to find methods `toString` and `valueOf`:

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

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

By default, a plain object has following `toString` and `valueOf` methods:

- The `toString` method returns a string `"[object Object]"`.
- The `valueOf` method returns the object itself.

Here's the demo:

```js run
let user = {name: "John"};

alert(user); // [object Object]
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]`.

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 to customize the conversion.

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

```js run
let user = {
name: "John",
money: 1000,

// for hint="string"
toString() {
return `{name: "${this.name}"}`;
},

// for hint="number" or "default"
valueOf() {
return this.money;
}

};

alert(user); // toString -> {name: "John"}
alert(+user); // valueOf -> 1000
alert(user + 500); // valueOf -> 1500
```

As we can see, the behavior is the same as the previous example with `Symbol.toPrimitive`.

Often we want a single "catch-all" place to handle all primitive conversions. In this case, we can implement `toString` only, like this:

```js run
let user = {
name: "John",

toString() {
return this.name;
}
};

alert(user); // toString -> John
alert(user + 500); // toString -> John500
```

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

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

There is no control whether `toString` returns exactly a string, or whether `Symbol.toPrimitive` method returns a number for a hint `"number"`.

The only mandatory thing: these methods must return a primitive, not an object.

```smart header="Historical notes"
For historical reasons, if `toString` or `valueOf` returns an object, there's no error, but such value is ignored (like if the method didn't exist). That's because in ancient times there was no good "error" concept in JavaScript.

In contrast, `Symbol.toPrimitive` *must* return a primitive, otherwise there will be an error.
```

## Further conversions

As we know already, many operators and functions perform type conversions, e.g. multiplication `*` converts operands to numbers.

If we pass an object as an argument, then there are two stages:
1. The object is converted to a primitive (using the rules described above).
2. If the resulting primitive isn't of the right type, it's converted.

For instance:

```js run
let obj = {
// toString handles all conversions in the absence of other methods
toString() {
return "2";
}
};

alert(obj * 2); // 4, object converted to primitive "2", then multiplication made it a number
```

1. The multiplication `obj * 2` first converts the object to primitive (that's a string `"2"`).
2. Then `"2" * 2` becomes `2 * 2` (the string is converted to number).

Binary plus will concatenate strings in the same situation, as it gladly accepts a string:

```js run
let obj = {
toString() {
return "2";
}
};

alert(obj + 2); // 22 ("2" + 2), conversion to primitive returned a string => concatenation
```

## Summary

The object-to-primitive conversion is called automatically by many built-in functions and operators that expect a primitive as a value.

There are 3 types (hints) of it:
- `"string"` (for `alert` and other operations that need a string)
- `"number"` (for maths)
- `"default"` (few operators)

The specification describes explicitly which operator uses which hint. There are very few operators that "don't know what to expect" and use the `"default"` hint. Usually for built-in objects `"default"` hint is handled the same way as `"number"`, so in practice the last two are often merged together.

The conversion algorithm is:

1. Call `obj[Symbol.toPrimitive](hint)` if the method exists,
2. Otherwise if hint is `"string"`
- try `obj.toString()` and `obj.valueOf()`, whatever exists.
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 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