Skip to content

Commit c738e37

Browse files
committed
fixes
1 parent 80ea234 commit c738e37

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

1-js/05-data-types/05-array-methods/article.md

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -655,31 +655,37 @@ arr.map(func, thisArg);
655655

656656
The value of `thisArg` parameter becomes `this` for `func`.
657657

658-
For instance, here we use an object method as a filter and `thisArg` helps with that:
658+
For example, here we use a method of `army` object as a filter, and `thisArg` passes the context:
659659

660660
```js run
661-
let john = {
662-
age: 18,
663-
younger(otherUser) {
664-
return otherUser.age < this.age;
661+
let army = {
662+
minAge: 18,
663+
maxAge: 27,
664+
canJoin(user) {
665+
return user.age >= this.minAge && user.age < this.maxAge;
665666
}
666667
};
667668

668669
let users = [
669-
{age: 12},
670670
{age: 16},
671-
{age: 32}
671+
{age: 20},
672+
{age: 23},
673+
{age: 30}
672674
];
673675

674676
*!*
675-
// find all users younger than john
676-
let youngerUsers = users.filter(john.younger, john);
677+
// find users, for who army.canJoin returns true
678+
let soldiers = users.filter(army.canJoin, army);
677679
*/!*
678680

679-
alert(youngerUsers.length); // 2
681+
alert(soldiers.length); // 2
682+
alert(soldiers[0].age); // 20
683+
alert(soldiers[1].age); // 23
680684
```
681685

682-
In the call above, we use `john.younger` as a filter and also provide `john` as the context for it. If we didn't provide the context, `users.filter(john.younger)` would call `john.younger` as a standalone function, with `this=undefined`. That would mean an instant error.
686+
If in the example above we used `users.filter(army.canJoin)`, then `army.canJoin` would be called as a standalone function, with `this=undefined`, thus leading to an instant error.
687+
688+
That said, a call `users.filter(user => army.canJoin(user))` also guarantees the correct `this`, and it's more obvious what's going on, so in practice the arrow function is used most of time, instead of `thisArg`.
683689

684690
## Summary
685691

0 commit comments

Comments
 (0)