Skip to content

Chapter: Variable scope, closure, modification suggestion #2068

Description

@ajfg93

There is an "Army of functions" exercise in this chapter. And I suggest some modifications for the explanation/solution.

If I understand correctly, using let doesn't create a new Lexical Environment and it is the {} block clause creates a new Lexical Environment each time and let just creates a local variable inside the Lexical Environment, while var hoists the variable into the function level scope when creating a variable. So, whether using let or not, there is a new Lexical Environment created each run in for(){} or while{}.

But for the first time I read the solution/explanation, I thought it was using let that creates a new Lexical Environment. Kinda misleading until I read some thing on MDN about let.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above.

The quotes above did not direclty clear my doubt but made me thought twice. And then I got my coherent conclusion.


Parts that made me mostly confused for the first time:

Now it works correctly, because every time the code block in for (let i=0...) {...} is executed, a new Lexical Environment is created for it, with the corresponding variable i.

The while loop, just like for, makes a new Lexical Environment for each run. So here we make sure that it gets the right value for a shooter.

And becasue you are adding a new let or replacing var with let in each new code snippet. So I was more likey to believe that it was let that somehow creates a new Lexical Environment.

To sum up, I suggest making some modification here and let the readers know let does not create a new Lexical Environment, while {} does.

Anyway, it's just my opinion. (Or my conclusion could totally be wrong. I write C++ most of my times.)

--

In the end, I would like to thank you so much for the tutorial. It's so far the best I could find in the Net. So much better than the classic book I've read. I am going to buy a full tutorial.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions