3

Calling a Javascript function with something like

someFunction(1, true, 'foo');

is not very clear without familiarity with the function.

I have seen and used the style where comments are inserted to name the arguments:

someFunction(/*itemsToAdd*/1, /*displayLabel*/ true, /*labelText*/ 'foo');

But when it gets beyond 3 or more parameters, it seems better to pass arguments in a JSON object which makes it order-independent, and allows default values to be provided in the called function

someFunction({'itemsToAdd':1, 'labelText':'foo', 'displayLabel':true});

My question is; what is the general practice in the industry, and are there overriding reasons for not using any of these methods. Lint for example does not like the second method.

2
  • 1
    If you use something like Coffeescript that has destructuring assignments, that last style gets very convenient.
    – Thilo
    Jul 11, 2013 at 10:00
  • 1
    This addresses the problem with the comments style. Seems the second is more common.
    – jpmc26
    Aug 24, 2013 at 6:30

1 Answer 1

0

Personally I'd just grep the function name and take a look at the comment associated with it. Well maintained code will have a comment above the function explaining what the arguments are and what it does with them, and you can just paste that above the function call if you need to explain why your arguments are the way they are.

Using a JSON to pass arguments seems like a way to add unnecessary parsing overhead and to possibly confuse the maintainer - just add more fields and pass in NULLs to the fields where you want default values, and you can explain why you're passing in NULLs in the call comment instead of just having them not appear in the JSON.

3
  • 2
    He is just incorrectly calling javascript objects JSON, there is actually no JSON or JSON parsing involved.
    – Esailija
    Jul 11, 2013 at 10:04
  • Esailija, thanks for your reply. I thought JSON was the notation used to create a JS object. Is my 3rd example not JSON? I'll google now, but an explanation might be useful for other readers. Jul 15, 2013 at 17:36
  • JTravakh, thanks. I agree that comments are essential in any event, I was just hoping to avoid the constant back-and-forth checking the order and meaning of parameters when writing the code.Especially when the function is in another module/file. The third method ("JSON" thing) just seems more memorable and fault-friendly. Writing code is quicker, and reading is much easier therefore bug detecting easier. JavaScript seems to run at 70% of machine code so in most cases parsing overhead would not be noticeable, yes? Jul 15, 2013 at 17:45

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