Created
October 15, 2021 12:32
-
-
Save robertocarroll/cacd82be3aeff0fab6b5694345ad65bd to your computer and use it in GitHub Desktop.
Using object destructuring to make cleaner and better functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gomakethings.com/destructuring-function-parameters-with-vanilla-js-for-better-developer-ergonomics/ | |
// use curly brackets inside the function arguments and then set defaults inside | |
function greet ({greeting, name, time = 'today'}) { | |
return `${greeting} ${name}! How are you ${time}?`; | |
} | |
// returns "Hello George! How are you today?" | |
let message = greet({ | |
name: 'George', | |
greeting: 'Hello' | |
}); | |
//https://javascript.plainenglish.io/use-this-pattern-to-make-your-javascript-functions-more-extensible-5c93ee47dc33 | |
async function postData({ | |
url, | |
data, | |
baseUrl = 'http://api.example.com/', | |
headers: {} | |
}) { | |
const response = await fetch(`${baseUrl}${url}`, { | |
method: 'POST', | |
body: JSON.stringify(data), | |
headers | |
}); | |
return response.json(); | |
} | |
//call the function | |
const res = await postData({ | |
url: '/an-endpoint', | |
data: { some: data }, | |
headers: { authorization: '...' } | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment