Check out our Angular Book Series.

How do I combine Objects in JavaScript? Use the Ellipsis Operator!

This is a followup to last week's post about using Object.assign() to combine two JavaScript objects. Today I'll show you how to use the spread, or ellipsis, operator to do the same thing.

The scenario is that we have a configuration object being passed into a method. A lot of the config values are optional, and we want to default them if they are left out before the method does it's magic. We could write a lot of manual conditions to accomplish this, like this:


function conditionalConfig(config){
if(!config.option1){
config.option1 = defaultOption1Value;
}
if(!config.option2){
config.option2 = defaultOption2Value;
}
// etc.. etc.. etc..
// do other stuff
}

The code works, but it is tedious to write. We can use the Spread Operator to simplify it.

The Spread Operator

The spread operator is an ellipsis, or three dots. It has a handful of uses, but today I'm going to show you how to combine two objects.

Start with a function and an object that contains all the default values:


function defaultConfigWithSpread(config){
defaultObject = {
option1 : 'DefaultValue1',
option2 : 'DefaultValue2',
option3 : 'DefaultValue3',
option4 : 'DefaultValue4',

Notice I didn't close the object yet. We have one more property to add to the object:


...config
}

That last property is our spread operator. It tells the underlying engine to take all the properties from the config object and copy them into the defaultObject. If a property already exists in the defaultObject, it is overwritten. If a property does not exist it will not be changed.

For demonstration purposes, log the two objects:


console.log(config);
console.log(defaultConfig);
// do other stuff
// end function
}

You can test this like this:


customConfigObject = {
option1 : 'Value1',
option2 : 'Value2',
option3 : 'Value3',
}
defaultConfigWithSpread(customConfigObject);

Look at the console output and you'll see that the original config object is unchanged, but the default object contains all the new values:

The custom values from our config argument are retained and the unset default value--option4--is set with the new config.

You have to be careful when doing this to keep around a clean version of the default object since it is modified with this approach. I addressed that by creating the default config inside the function, as opposed to some permanent store.

Play with the code here.

It is a nice shorthand to be aware about.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.