Cool Javascript 9: Named arguments — Functions that get and return Objects

Brought to you by Object destructuring and shorthand property names!

// some code...apiRequest(
'products',
'GET',
{ category: 3 },
["Content-Type: text/plain"],
function(response) { ... },
null,
true
)
// some more code...

Enter object destructuring and shorthand property names!

var someObject = { a: 1, b: 2, c: 3 }
var { a: a, b: b, c: c } = someObject
var someObject = { a: 1, b: 2, c: 3 }
var { a, b, c } = someObject
The “timeout: 0” makes *no* sense but I’m literally too lazy to open, edit, save, copy, remove from the post and paste the Gist again ❤.

But wait, there’s more!

var someObj = { a: 1, b: 2 }var {
a,
b,
c = 123456,
} = someObj
// a = 1
// b = 2
// c = 123456
apiRequest({
endpoint: 'products',
getParams: { category: 3 },
})
function authApiRequest (params) {
const token = 'Bearer whatever'
return new Promise((resolve, reject) => {
apiRequest(
...params,
{ headers: ...params.headers, Authentication: token }
)
.then(resolve)
.catch(reject)
}
}
function postRequest (params) {
return new Promise((resolve, reject) => {
apiRequest(...params, method: 'POST')
.then(resolve)
.catch(reject)
}
}

You can use the same pattern with returning values

function apiRequest({ ... }) {
var response, error, loading
response = error = loading = null
//some amazing code... return {
response,
error,
loading,
}
}
var { response, error, loading } = apiRequest({ ... })

Recap: benefits of passing and receiving objects as parameters

Warning #1: This is not an excuse to create monstruous function signatures

function getUsersList ({ includeInactiveUsers = false }) {...}getUsersList()     // what
getUsersList(true) // the fuck
function getActiveUsersList() { ... }function getInactiveUsersList() { ... }function getUsersList() {
return [...getActiveUsersList(), ...getInactiveUsersList()]
}

Warning #2: This is just a pattern

--

--

Words matter – Software product development, Front-end, UX, design, lean, agile and everything in between. https://afontcu.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrià Fontcuberta

Words matter – Software product development, Front-end, UX, design, lean, agile and everything in between. https://afontcu.dev