Sai Charan
Sai Charan

Reputation: 153

How to pass an extra parameter despite having default parameters in Javascript?

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?

Upvotes: 2

Views: 113

Answers (5)

Jai
Jai

Reputation: 74748

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]);

Upvotes: 3

meriton
meriton

Reputation: 70584

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});

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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>

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122155

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}))

Upvotes: 0

myxobek
myxobek

Reputation: 455

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

Upvotes: 1

Related Questions