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?

Sai Charan
  • 123
  • 1
  • 2
  • 8
  • http://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function#894877 – ZiTAL Apr 10 '17 at 11:48

5 Answers5

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]);
Jai
  • 74,255
  • 12
  • 74
  • 103
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
myxobek
  • 445
  • 3
  • 10
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}))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
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});
meriton
  • 68,356
  • 14
  • 108
  • 175