Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - Cannot use let to define a variable with the same name of function's parameter

I am returning to javaScript after a long absence and I've just learnt about ES6 new features. And here it comes the first doubt.

Although I understand that a let variable cannot be declared twice in the same block scope I came across this situation:

    function tell(story){
       let story = {
          story
        };
     }

And it gives me a error: Uncaught SyntaxError: Identifier 'story' has already been declared

Using var this works just fine.

1) Does this mean that I will have to declare a variable with a different name of the function's parameter using let (or even const)? This can be very annoying in terms of variable naming.

In order to keep the same name I did:

function tell(story){
     story = {
        story
     };
}

2) In this case the variable story will belong exclusively to the scope of the function tell?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using var this works just fine.

Not really, the var is completely ignored, and you'd effectively have:

function tell(story){
   story = {
      story
   };
 }

If that's what you want, just leave the var (and let) off entirely (as above).

The error from let addresses this pitfall, where you think you've created a (new) variable but haven't. You can't use let (or const) to declare a variable that's already declared in the same scope (either as a variable, or as a parameter, which is almost the same thing as a variable).

1) Does this mean that I will have to declare a variable with a different name of the function's parameter using let (or even const)? This can be very annoying in terms of variable naming.

That's up to you. To keep doing what you were doing, just leave off var, let, and const entirely, because again, the var had no effect at all and you were assigning to the parameter, not a new variable. Or keep doing what you were doing (with var), but understand that it's misleading. Or use a different name with let or const — there are many who believe changing the value of a parameter isn't best practice (personally I'm not one of them, but...) and they'd recommend a different variable instead.

2) In this case the variable story will belong exclusively to the scope of the function tell?

Yes, you're assigning to the parameter story, which is local to tell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...