viery365
viery365

Reputation: 965

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?

Upvotes: 4

Views: 1349

Answers (2)

TheEddWardd
TheEddWardd

Reputation: 21

"the var is completely ignored"

Not really, consider the following two examples:

1:

function someFn(a, b = () => a) {
  console.log(a, b());

  a = 2;
  
  console.log(a, b());
}
someFn(3);

2:

function someFn(a, b = () => a) {
  console.log(a, b());

  var a = 2;
  
  console.log(a, b());
}
someFn(3);

In the first example the output will be:
3 3
2 2
And in the second one:
3 3
2 3

So var does matter.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074108

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.

Upvotes: 6

Related Questions