Skip to content

Instantly share code, notes, and snippets.

What would you like to do?

And the famous answer is: it depends. Depends on the use case.

Use case #1: Optional parameters

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
// Optional params
$http.get('', {
  headers: {
    'Accept': 'text/html'
// we could have a function that has only optional parameters?

Use case #2: Clarity

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
	cx: 100,
	cy: 100,
	rx: 50,
	ry: 75,
	rotation: .785398

Use case #3: It should really be an object

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' };

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.