1

I have a function with many parameters and many default value on them.

function foo(p1 ,p2, p3, p4, p5, p6){
    var p1 = p1 || 'default1'; 
    var p2 = p2 || 'default2'; 
    var p3 = p3 || 'default3'; 
    var p4 = p4 || 'default4'; 
    var p5 = p5 || 'default5'; 
    var p6 = p6 || 'default6'; 
}

How can I successfully only define like p1 and p6 only and not the rest?

I know in Scala you can do foo(p1='something1',p6='something6')

3 Answers 3

5

You should take an object with properties for parameters.

For example:

function foo(options) {
    var p1 = options.p1 || 'default1'; 
    ...
}

foo({ p1: 3, p6: "abc" });
Sign up to request clarification or add additional context in comments.

2 Comments

You could additionally loop through the options object and another object to minimize code size.
This also answers my question of "How to prevent writing a function with many parameters?"
2

You could use one parameter that is an object and do jQuery extend for defaults like:

function foo(args) {
   jQuery.extend({
      p1: 'default1',
      p2: 'default2',
      p3: 'default3',
      p4: 'default4',
      p5: 'default5',
      p6: 'default6'
   }, args);
}

foo({p1: 'one', p6: 'six'});

Any properties defined in the second parameter to extend will overwrite properties in the first parameter.

2 Comments

Yeah, it's not necessary. You could just define the defaults as in the question like you did. Our answers would then be the same though, and that's not any fun ;)
Having that function is essential, jQuery or no: function extend(dest, src) { for (prop in src) dest[prop] = src[prop]; return dest } (naive implementation). This is the best option for constructor functions when inheriting, as you don't have to gather up all the values to pass onto the parent constructor when calling it - just apply your own required defaults with extend and do ParentConstructor.call(this, args).
1

Those are referred to as "named parameters", and there are several tutorials on them (using objects like in @SLaks's answer):

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.