And the famous answer is: it depends. Depends on the use case.
If the parameters are optional, you may use a single parameter (generally named options
) to receive and conditionally Object.assign
the default values (mostly used in pre-ES6 code, but still has its use).
jQuery uses this approach in lots of functions. Here's an example from Angular's $http.get:
// No params
$http.get('https://httpbin.org/get');
// Optional params
$http.get('https://httpbin.org/get', {
headers: {
'Accept': 'text/html'
}
});
// we could have a function that has only optional parameters?
If the parameters of a function have no clear meaning, it's better to pass a object, mocking the feature of named parameters from some languages. Lea Verou covers this topic beautifully in her JSUX talk (check out slide #55 and after):
// instead of this
ctx.ellipse(100, 100, 50, 75, .785398);
// use this
ctx.ellipse({
cx: 100,
cy: 100,
rx: 50,
ry: 75,
rotation: .785398
});
Let's say you have a function to save an user. You can receive all user information in a single object:
let user = { name: 'Mario', password: 'p34ch' };
api.saveUser(user);
I may have missed more use cases, but here are some. Using object literals isn't a sin, but using them wrong may lead to bad code UX - after all, "code is written once and read many times".