preface

Recently, I read the book “YOU DON’t KNOW JS”, which talked about the nesting of scope, the content mainly talked about two points:

One is the origin of scope nesting. In fact, when a block or function is nested in another block or function, the nesting of scope takes place.

The second is the rule for finding variables. The engine looks for variables from the current execution scope, and if it can’t find them, it looks up one level. When the outermost global scope is reached, the search process stops whether it is found or not

There’s another analogy that I think is interesting and helps us understand scoping chains very well, and I’ll share the original paragraph

Think of the scope chain as a building

The author compares the scope chain to a building, which represents a nested scope chain in a program. The first floor represents the current execution scope, which is where you are. The top level of the building represents the global scope.

Both LHS and RHS references look up on the current floor, and if they can’t find one, they take the elevator to the next floor, and if they still can’t find one, they go up, and so on. Once you reach the top level (global scope), you may or may not have found the variables you need, but the search will stop anyway, right

The resources

YOU DON’t KNOW JS vol. 1