JavaScript Sprint Tricks #14

Once again, this sprint has unveiled a few new ways that we can use to write shorter and more readable JS. Check for yourselves!

1. Require arguments (@andrew)

Here’s how you can throw if required argument was not passed:

// this function just throws when called
const required = () => {
  throw new Error('Called without a required argument.')
}

// ...and it'll only be called if argument is not provided
const log = (message = required()) => {
  console.log(message)
}

log('Hello') // this won't throw
log() // this will

Nice thing about this approach is the clear visibility of requirement right in the function declaration. 👀

2. Filter falsy values (@mike)

Here’s the simplest of 1001 ways to filter falsy values in an array:

[0, 1, '', 'hello', null, false, true]
  .filter(Boolean)
  
// returns [1, 'hello', true]

Really short and neat, huh? 🤩

3. Merge default options (@dominic)

Here’s how you can use the spread operator to merge many levels of opts:

const commonOpts = {
  log: false
}

const processData = (opts) => {
  const defaultOpts = {
    maxIterations: 10
  }
  
  opts = {...commonOpts, ...defaultOpts, ...opts}
  
  // use opts to process data
}

For pity’s sake, just don’t add the 4th level… 🤯

That’s it for this week. Send your own pick to @karol and join the elite club of pragmatists in our team!