Skip to content

Instantly share code, notes, and snippets.

@robertocarroll
Created October 15, 2021 12:32
Show Gist options
  • Save robertocarroll/cacd82be3aeff0fab6b5694345ad65bd to your computer and use it in GitHub Desktop.
Save robertocarroll/cacd82be3aeff0fab6b5694345ad65bd to your computer and use it in GitHub Desktop.
Using object destructuring to make cleaner and better functions
// 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