-1

What do I pass in for the existing arguments that have no value, undefined or null?

Existing function foo(a, b) is called like foo(1) and foo(23, "hi"). After adding a new parameter, it's foo(a, b, c) and I want to change foo(1) to be foo(1, undefined, 3.2) or foo(1, null, 3.2).

Does null 'looking better' override the concern that existing code may already expect the second param to be undefined in some cases?

2
  • If you don't change the original calls the undefined is implicitly passed for the arguments you don't specify. Jul 14, 2018 at 0:37
  • @GregBurghardt We are aware of that.
    – Josh
    Jul 14, 2018 at 0:41

1 Answer 1

0

Assuming ES5

You should switch to passing objects to your function:

var foo = function(options){
    var first = options.first;
    var second = options.second;
    var third = options.third; 
    ...
}

This way, you have a much cleaner Interface foo({first:"Test", third:"Test3"})

You name the parameters, you want to set explicitely. This has the upside of no necessity to remember in which sequence the parameters have to be called and to remember whether null or undefined was the 2nd parameter and you see what maps to what.

Assuming ES6+

This becomes in ES6 parameter context matching:

const foo = ({first, second, third})=>{...}

foo({first:"Test", third:"Test3"})

There is a bit of implicit destructuring "magic":

foo({first:"Test", third:"Test3"})

behaves like

foo(obj)

and

const foo = ({first, second, third})=>{...}

is equivalent to:

const foo = (options)=>{
 const {first, second, third} = options;
 ...
}

which is equivalent to the ES5 solution with object matching (a subkind of destructuring) added.

And object matching behaves like the ES5 solution above.


tl;dr

Recommendation: Refactor your code, avoiding positional arguments at all.

3
  • 1
    +1 for Refactoring, however it might be infeasible to refactor an already existing function if it is used a lot. If that is the case, I’d write a differently named function for the new use case (i.e. with three arguments, or with an argument object), and delegate calls to the old, two-parameter function to the new one.
    – bleistift2
    Dec 25, 2019 at 9:38
  • @bleistift2 yes and no. Of course you are right it might be infeasible under certain circumstances. OTOH we are in the age of ever smarter IDEs which make it cheap to do that - supposed you have a good testsuite it should be a no brainer. Dec 25, 2019 at 10:32
  • It is totally ok to vote an answer down. But I would encourage people to do so openly and give reasons of why they downvoted it. And especically in this case, where the answer is technical sound and elaborate. Without giving reasons it feels like backstabbing, Dec 28, 2019 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.