re: Array's Avengers: forEach(), filter(), map() and reduce() VIEW POST


Very detailed and I love the analogy! One thing though - you are passing a this when calling forEach etc with a fat arrow function. That doesn't do anything. Passing a this is useful when using real functions or class methods/prototypes etc.

This example illustrates it, I've commented what it logs:

class MyClass {
  constructor(value) {
    this.value = value;
  predicate(item) {
    return item === this.value;

const hello = new MyClass("hello");
const goodbye = new MyClass("goodbye");
const array = ["hello", "goodbye", "goodbye", "hello", "hello"];
console.log(array.filter(hello.predicate)); // -> []
console.log(array.filter(hello.predicate, hello)); // -> ["hello", "hello", "hello"]
console.log(array.filter(goodbye.predicate)); // -> []
console.log(array.filter(goodbye.predicate, hello)); // -> ["hello", "hello", "hello"]
console.log(array.filter(goodbye.predicate, goodbye)); // -> ["goodbye", "goodbye"]
array.filter(item => {
  console.log(this); // -> undefined
  return item === "hello";
array.filter(item => {
  console.log(this); // -> undefined
  return item === "hello";
}, hello);

Which isn't what people often expect :)

In a fat arrow the this is always the this of the calling context.


Thanks for sharing your views.
Actually, I tried to use the simplest examples and focused more on explaining the parameters than actually going deep into the classes concept.

Will try to give better examples in my future articles.🙇

code of conduct - report abuse