Neat tricks with JavaScript

June 29, 2021
views 2 min read

There are a few tricks I use on a daily basis. I got so used to it then I got the sense that every single developer knows about it.

That can definitely be the case, or not, take a read.


Conditional operator in objects

While building objects, usually to send data to an API, I don't always want to send all data from a form. I tend to use the conditional operator:

const { name, age, twitter, address } = values

const data = {
  name,
  age,
  twitter,
  ...address && { address },
}

This will only include address if it's available within values.


Option chaining with mapping

Before optional chaining while mapping an array I would do something like this:

values && values.map(({ age }) => age)

Now I only use values?.map, small change, but much cleaner:

values?.map(({ age }) => age)

Specially that with the first option it'll actually return null, with the second option nothing happens in case values doesn't exist.


Or else

This is totally a personal opinion, but I hate using else, this obviously also depends from company to company. Some companies prefer using else, I don't like it, check the following example:

const name = "Telmo"

function greeting() {
  if (name) {
    return `The name is ${name}.`
  } else {
    return `We still don't have a name.`
  }
}

greeting()

This is totally fine and it works as expected. Although I prefer to use this way:

const name = "Telmo"

function greeting() {
  if (name) return `The name is ${name}.`

  return `We still don't have a name.`
}

greeting()

Re-use

Say you have multiple inputs in a page, we'll use 3 for this example:

<input
  type="text"
  placeholder="Name"
  required
/>

<input
  type="text"
  placeholder="Twitter"
  required
/>

<input
  type="text"
  placeholder="Polywork"
  required
/>

Again, nothing wrong with this. Although, you might notice that at least 2 properties in each input are exactly the same.

We can take advantage of spreading properties:

const inputProps = { type: 'text', required: true }

<input {...inputProps} placeholder="Name" />

<input {...inputProps} placeholder="Twitter" />

<input {...inputProps} placeholder="Polywork" />

That's a wrap

I'm sure there's a lot more that I can't even recall now. But I guess these are really handy.

Read next
How to set default values while destructuring
January 14, 2021
views