0

Sometimes I see two different ways to define default value for function arguments.

The first one is to redefine argument value like that:

var callName1 = function( name ) {
 name = name || 'John';
 console.log( 'Hello, ' + name );
};

The second one is to define local variable with the same name:

var callName2 = function( name ) {
 var name = name || 'John';
 console.log( 'Hello, ' + name );
}

Both of this methods are working the same.
So, I have two questions:
1) What's the point to define local variable with same name in the second way?
2) Which of these ways is more correct?

2
  • 1
    First one is more correct since name is already defined in the function and there is no need for a redefinition. On the other hand in ES6 you can avoid both usages by the default argument values such as var callName1 = function(name = "John") {... Commented Nov 30, 2016 at 15:29
  • essentially there is no difference, however here is a difference when you try to convert your code with some optimizers though, making vars into lets and such, it confuses them sometimes. Commented Nov 30, 2016 at 15:36

1 Answer 1

6

There is no difference between them. var statements for variables which are already local to the function have no effect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.