0

I have a function which has two default parameters and one regular parameter.

var Fields = function ($content, result = failedObject, job = true) 
{
    ...
}  

When I call Fields($content,job), job here could be true or false, the result parameter takes in the job value rather than the third parameter. Works good in the case if Fields($content,result).

Any good way to tackle this situation.

zronn
  • 1,026
  • 8
  • 26
Devuatprod
  • 147
  • 1
  • 11

5 Answers5

2

you would call Fields($content, undefined, job) to use the default value for the parameter result

dikuw
  • 1,134
  • 13
  • 22
1

You could use a destructured argument :

var Fields = function ($content, { result = failedObject, job = true } = { }) {
    ...
}

Then, when you call the function :

const data = { result: anotherObject, job = false };
Fields('toto', data);

Or, in your specific case :

const data = { job = false };
Fields('toto', data); // result still is a failedObject
zronn
  • 1,026
  • 8
  • 26
1

if I understood your question correctly, javascript does not support named parameters natively, so you can call by Fields($content, undefined, job)

or using an object as parameter for your function instead of 3 params.

IWHKYB
  • 481
  • 3
  • 11
0

Pass empty/undefined/null:

Fields($content, , job);

Rob Wood
  • 415
  • 5
  • 11
  • 1
    `Fields($content, , job)` is syntax error. Passing `null` will set param value to `null`. Only `undefined` is proper way. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Passing_undefined_vs._other_falsy_values – ponury-kostek Jul 18 '19 at 15:43
  • yeah exactly only undefined would work . – Devuatprod Jul 18 '19 at 15:45
-1

You must switch the order(like below), or using an array and treat inside function.

var Fields = function ($content, job = true, result = failedObject, ) 
     {
     }
Ricardo CF
  • 79
  • 5