legotin legotin - 1 year ago 118
Javascript Question

Defining function arguments as local variables

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download