JavaScript Spread Operator

QuickTip JavaScript

When dealing with many different objects in JavaScript, sometimes you need to compile them all down together. The spread operator is a handy function for this and more.

Merging Objects

Sometimes, you need to easy recombine the elements of multiple objects, spread operator makes this simple.

Quick Example:
 
const veggies = { onions: 2, potatoes: 3 };
const fruits = { apples: 2, bananas: 4 };

const inventory = {...veggies, ...fruits};

/*
 { onions: 2, potatoes: 3, apples: 2, bananas: 4 }
*/

Combining Arrays 

In a similar way, the spread operator can help when trying to combine arrays. 

const user_list_1 = [232,567,344,74];const user_list_2 = [109,34,224,920];
const all_users = {...user_list_1, ...user_list_2};

/*
[
  232, 567, 344,  74,
  109,  34, 224, 920
]
*/


Similar Posts

Refactoring Rails: Use REST

Just some notes / key takeaways from the course "Refactoring Rails" by the great Ben Orenstein.

WebDev Rails

Debugging AWS S3 for Rails Active Storage

It could be your CORS configuration for AWS S3 for Rails ActiveStorage

Tech WebDev Rails

Simple Full Text Search in Rails

No gems, no dependencies, no complexity. Here’s a basic full text search to use on simpler, smaller rails apps.

WebDev Rails

Refactoring Rails: Form Objects

Form objects let you work with many objects at once in rails. It's a pattern that's a lot more powerful and clean than accepts_nested_attributes.

WebDev Rails