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

后端 未结 1 1379
遥遥无期
遥遥无期 2020-12-21 06:09

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

相关标签:
1条回答
  • 2020-12-21 06:34

    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.

    0 讨论(0)
提交回复
热议问题