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

Incentives

Companies seem to be completely blind to the insanity of the incentives they choose to track.

business

Refactoring Rails: Use REST

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

WebDev Rails

Spinning Up a New Rails App

Bookmarking this incredible tool

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