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.

1
  • What exactly is your question? Commented Jul 18, 2019 at 15:33

5 Answers 5

2

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

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

Comments

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.

Comments

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

6 Comments

Downvoting, no comment ?
There is no need to change function signature. Just pass undefined as param value
What if OP can't change function signature?
@ponury-kostek I'm just suggesting a another possible solution, OP doesn't says he wants to keep the same signature
So why not to pass all parameters in single object?
|
0

Pass empty/undefined/null:

Fields($content, , job);

2 Comments

Fields($content, , job) is syntax error. Passing null will set param value to null. Only undefined is proper way. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
yeah exactly only undefined would work .
-1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.