Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in this code snippet is the outer scope of the arrow function in `showList` instead of `forEach`?

So here is the code snippet from this modern JavaScript tutorial:

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(
      student => alert(this.title + ': ' + student)
    );
  }
};

group.showList();

The tutorial tries to explain this in an arrow function, and it says:

Here in forEach, the arrow function is used, so this.title in it is exactly the same as in the outer method showList. That is: group.title.

We know this in an arrow function is determined lexically. So the scope chain should be:

global--> showList-->forEach-->arrow function

In this case, the outer scope of arrow function should be forEach instead of showList. Thus this in an arrow function is exactly the same as in forEach, which should be undefined since there is no thisArg passed to forEach. But in fact, this is group, which means it is exactly the same as in showList. So, it seems forEach doesn't hold a scope in this case? I am confused.

like image 818
Chor Avatar asked Jan 25 '23 11:01

Chor


1 Answers

So the scope chain should be:

global--> showList-->forEach-->arrow function

I think you are confused what "scope" means. It's a variable scope, in code typically delimited with braces {…}, the region in which any identifier always refers to the same variable.

There is no "forEach scope". It's just a function call. Just like there is no scope for the parameter list of the alert(…) call. There are only three scopes in your example:

global --> showList --> anonymous arrow function

There is also the call stack, outlining which function calls led to the execution of the current code. This does indeed contain forEach, which is calling the arrow function, which in turn will call the alert function. But this does not correspond to the scope in JavaScript (for which you will see more examples when learning about closures), which is why JavaScript is said to have lexical scope and not dynamic scope (where identifiers are resolved dynamically depending on where a function was called).

like image 197
Bergi Avatar answered Feb 05 '23 05:02

Bergi