2

Consider the example

var example = function(a = 10, b = 15, c) {
 return c;
}

So, I want to call the example function with just the value of c. Something like,

example(20); // should return 20, without disturbing the values of a and b

How would I do this in JavaScript?

1

5 Answers 5

3

What you want is can be achieved with destructring assignment but it needs some mods. As i can see you are using es2015/es6 code for setting the default values. You might consider this:

var example = function([a = 10, b = 15, c]) {
   console.log(a,b, c);
   //return c;
}

example([,,20]);

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

Comments

1

You should consider using predefined variables in the end of function declaration:

var example = function(a, b = 10, c = 15 ) {
    return a;
}

So result would be

example(20); // ->> 20

Comments

0

You could pass null as arguments for a and b when you call example.

var example = function(a = 10, b = 15, c) {
 return c;
}

console.log(example(null, null, 20))

Or you could just use object as parameter.

var example = function(obj) {
 obj.a = obj.a || 10;
 obj.b = obj.b || 15;
 return obj.c;
}

console.log(example({c: 20}))

Comments

0

You may have to use object instead :

var example = function(passed_options) {
   $.extend( default_options, passed_options );

   return c;
}

Hope this helps.

Sample snippet :

var example = function( passed_options ) {
   $.extend( {a: 10, b: 15}, passed_options );

   return passed_options.c;
}

console.log( example({c: 20}) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

0

You can use a parameter object to simulate named parameters:

var example = function(params) {
    const a = params.a || 10;
    const b = params.b || 15;
    const c = params.c || 20;
}

and invoke:

example({c:42});

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.