Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default Named Parameter Functions for Everything #4

Open
corysimmons opened this issue Apr 21, 2020 · 1 comment
Open

Default Named Parameter Functions for Everything #4

corysimmons opened this issue Apr 21, 2020 · 1 comment

Comments

@corysimmons
Copy link
Owner

corysimmons commented Apr 21, 2020


pubDate: 2016-10-11

image

I'm starting to wonder if we should just use named params for everything. They provide a lot of flexibility with no side-effects that I know of.

Here's how you do it:

const foo = ({a = 1, b = 2}) => console.log(`a: ${a}\nb: ${b}`)

foo({})
// a: 1
// b: 2

foo({b: 3})
// a: 1
// b: 3
  • We don't have to pass any smelly stuff like foo(undefined, 3).
  • Our parameter is more descriptive.
  • Our parameter is more flexible because it's not bound to any order-of-appearance.

Equal sign when setting defaults. Colon to assign when calling.

Yes, now you have to at least pass an empty object to your functions, and yes, we're forcing people to pass objects at all times, but there's probably an argument to be made about objects being more flexible anyway, and all-in-all, these are small prices to pay for how nice default arguments and named params are.

Named params have always been one of my favorite features of a language. JS doesn't seem to support a super-clean (still have to pass these as objects) way to do this, but at least now we can do it somewhat elegantly.

Now... if only there was a way to type-check those params...

@corysimmons
Copy link
Owner Author

corysimmons commented Aug 12, 2021

Another method using logical nullish assignment:

const foo = opts => {
  opts ??= {}
  opts.street ??= '123 Main St.'
  opts.city ??= 'NYC'
  opts.state ??= 'NY'

  console.log(`
    ${opts.street}
    ${opts.city}
    ${opts.state}
`)
}

// or

const foo = (opts = {}) => {
  opts.street ??= '123 Main St.'
  opts.city ??= 'NYC'
  opts.state ??= 'NY'

  console.log(`
    ${opts.street}
    ${opts.city}
    ${opts.state}
`)
}

foo() // gets rid of having to pass an empty object, as well as detecting nullish

Credit to https://github.com/whaaaley for pointing this out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant