0

When dealing with a function that in its definition accepts several arguments...

function f(foo, bar, baz){ ... };

...it's easy accidentally misplacing the arguments in the function call:

//'baz' is being passed as argument to 'bar' parameter
f(foo, baz, bar);
function f(foo, bar, baz){ ... };

That said, what I do when writing a code with a given function that I keep changing by adding more and more parameters in its definition (I'm the one writing both the function definition and the function calls) is using a mix of property shorthand and destructuring, so I don't need to be worried memorising the order of the parameters, which is handy when we have lots of them:

//this will work, regardless the order
f({bar, foo, baz});
function f({foo, bar, baz}){ ... };

Question: will that strategy always work? That is, will it work for any kind of type (primitives, arrays, dates, sets, maps, functions etc...)?

  • 3
    Sure, that'll work. In non-trivial projects, TypeScript helps a lot too with this and similar problems. – CertainPerformance Jul 09 '22 at 01:44
  • "*will it work for any kind of type?*" - why wouldn't it? – Bergi Jul 09 '22 at 01:44
  • @Bergi I don't know, that's why I asked... suppose that in the dark corners of javascript specs there's something strange, like *"hey, symbol won't work with this approach"*... I just wanted to check if this will ever break. By the way, off-topic question: is this an anti-pattern, or is this reasonable? –  Jul 09 '22 at 01:47
  • 1
    Creating an object and destructuring it has the same semantics as directly passing the values. Of course the signature of the function will be different, meaning different `f.length`, `f.bind(…)` for partial application won't work, etc. [It's reasonable and common](https://stackoverflow.com/q/11796093/1048572) if you have many parameters, but don't overuse it. Often a standard convention (e.g. OOP "subject first") is enough to alleviate the problem. For three parameters or less, it's often enough a nuisance having to spell out the property names everywhere. – Bergi Jul 09 '22 at 01:57

0 Answers0