3 Weird Things You (Probably) Didn't Know You Can Do With The JavaScript Spread Operator 🥳
Tags: javascript, node, tutorial, webdev
Published: 2020-01-30 12:59:49

---
title: 3 Weird Things You (Probably) Didn't Know You Can Do With The JavaScript Spread Operator 🥳
published: true
description: 3 uncommon uses for the JavaScript spread operator that you may not have seen before.
tags: javascript, node, tutorial, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/v3mb7qv56pqd68n51e8d.png
canonical_url: https://www.daysof.dev/javascript/three-weird-things-you-can-do-with-js-spread/
---

*If you find this post useful, you can sign up to my [mailing list](https://www.twosmalltrees.com/mailing-list), check out the other posts on my [blog](https://www.twosmalltrees.com), or follow me on [twitter](https://twitter.com/_twosmalltrees). I've also got a couple of active side projects that you might like to check out:*

* *[ippy.io](https://www.ippy.io) - An app for creating beautiful resumes*
* *[many.tools](https://many.tools) - A collection of useful utilities for designers and devs*

<hr />


The spread operator has been enthusiastically adopted by the JavaScript community since its inclusion in the language with ES6, with good reason! It vastly simplifies many common object and array manipulations patterns. 

While the common uses are widely appreciated and utilised, it also facilitates some slightly more obscure patterns.

Such as…


## 👉 1) Conditionally Adding Properties to an Object

It may not be *particularly* common, but imagine that (for whatever reason) you want to conditionally add properties to an object. Specifically, you want to add the properties if they hold a truthy value, but exclude them if they are null, undefined, or contain a falsey value. How might you approach this?

A reasonable approach might be something like the following:

```javascript
const firstName = 'Harrison'
const lastName = null
const address = '123 Street Rd'
const phoneNumber = null

const userInfo = {}

if (firstName) {
  userInfo.firstName = firstName
}

if (lastName) {
  userInfo.lastName = lastName
}

if (address) {
  userInfo.address = address
}

if (phoneNumber) {
  userInfo.phoneNumber = phoneNumber
}

console.log(userInfo)

// {
//   firstName: 'Harrison',
//   address: '123 Street Rd'
// }
```

There's nothing wrong with this approach - however using the spread operator, we can move the conditional logic inside the object literal. 

The result is somewhat more concise, and *in my opinion* once you've seen it a few times is actually more readable.

Take a look:

```javascript
const firstName = 'Harrison'
const lastName = null
const address = '123 Street Rd'
const phoneNumber = null

const userInfo = {
  ...firstName && { firstName },
  ...lastName && { lastName },
  ...address && { address },
  ...phoneNumber && { phoneNumber }
}

console.log(userInfo)

// {
//   firstName: 'Harrison',
//   address: '123 Street Rd'
// }
```

If you haven't seen this pattern before, it might take a second to grok what's going on. I'll try to explain:

Lets consider the first line inside the object literal, a case in which the property should be added to the object:

`...firstName && { firstName }`

Since `firstName` was previously assigned the truthy value `'Harrison'`,
the expression `firstName && { firstName }` will return `{ firstName: 'Harrison' }`. Both the left and right hand side of the `&&` evaluate as truthy, and as such the right hand side is returned.

This returned object is then spread into the `userInfo` object, resulting in the firstName property being successfully set.

Next, lets consider the alternate case, in which we attempt to assign a falsey value. Lets take the second line of the object literal:

`...lastName && { lastName }`

In this case, `lastName` is null. This means that the expression `lastName && { lastName }` short-circuits to returning the left hand side of the `&&`, which in this case is `null`.

We then attempt to spread `null` into the `userInfo` object. You might think this should result in an error, but it actually doesn't. 

In fact, as far as I'm aware spreading any falsey value into an object is perfectly valid syntax, but will result in no change to the object. Try it out:

```javascript
let obj = { ...null }
console.log(obj)
// {}

let obj = { ...undefined }
console.log(obj)
// {}

let obj = { ...false }
console.log(obj)
// {}

let obj = { ...'' }
console.log(obj)
// {}

let obj = { ...0 }
console.log(obj)
// {}

let obj = { ...{} }
console.log(obj)
// {}

let obj = { ...[] }
console.log(obj)
// {}
```

The end result of all this is that any truthy values will be added to the object, while any falsey values are left out! 

To make the code more explicit we can use the same pattern, but refactor the truthy check into its own function:

```javascript
const hasIfTruthy = (propertyName, property) => {
  return property && { [propertyName]: property }
}

const firstName = 'Harrison'
const lastName = null
const address = '123 Street Rd'
const phoneNumber = null

const userInfo = {
  ...hasIfTruthy('firstName', firstName),
  ...hasIfTruthy('lastName', lastName),
  ...hasIfTruthy('address', address),
  ...hasIfTruthy('phoneNumber', phoneNumber)
}

console.log(userInfo)

// {
//   firstName: 'Harrison',
//   address: '123 Street Rd'
// }
```

Using this pattern, you can even completely alter the condition that dictates whether a property is included or excluded - it doesn't necessarily need to be based on just truthy-ness/falsy-ness.

<hr />

## 👉 2) Spreading an Array into an Object

So… I'm yet to think of a particularly compelling reason that you would actually do this (shout out in the comments if you have one), but you can totally spread an Array into an Object. 

The result is that each array element is inserted into the object, with the key set to its respective array index.

Check it out:

```javascript
const fruitsArray = ['apple', 'orange', 'banano']

const fruitsObject = { ...fruitsArray }

console.log(fruitsObject)

// {
//   0: 'apple',
//   1: 'orange',
//   2: 'banano'
// }

```

<hr />

## 👉 3) Spreading a String Into an Array (or an Object)

This one is actually pretty nifty, and is probably more widely known than the others. You can spread a string into an array! 

The result is an array containing the individual characters from the string.

In my opinion this allows for a more pleasant syntax than the common `'string'.split('')` style.

Here it is:

```javascript
const characters = [..."apple"]

console.log(characters)

// ['a', 'p', 'p', 'l', 'e']
```

And if you're feeling really wild, you can even spread a string into an object 🙀

```javascript
const characters = {..."apple"}

console.log(characters)

// {
//   0: 'a',
//   1: 'p',
//   2: 'p',
//   3: 'l',
//   4: 'e'
// }
```
Stay safe out there kids.

<hr />

Know any other weird or wonderful uses for the JS spread operator? Let me know in the comments 😊