Cheatsheet for Spreading in JavaScript

Cheatsheet: Spread (Object or Array) in JavaScript

Today I’m gonna add a cheatsheet on how to work with spreading in JavaScript, both for Arrays and Objects. The support for the Object Spread operator ... in JavaScript is increasing rapidly (compat-table) Hot Tip:Add this page to your favorites so you can find it when you need it!

Spreading Arrays

1
2
3
4
5
const lowNumbers = [ 1, 2, 3];
const highNumbers = [4, 5, 6];
const [ one, ...restOfNumbers] = lowNumbers;
one; // 1
restOfNumbers; // [2, 3]

Copying Arrays

1
2
3
4
5
6
7
8
9
10
const lowNumbers = [ 1, 2, 3];
const cpy = [...lowNumbers]
cpy; // [1, 2, 3]

// Caveats -> The arrays are not "deep copied"
const deepArray = [[1], [2], [3]];
const notDeepCopy = [...deepArray];
notDeepCopy[0][0] = 9;
notDeepCopy; // [[9], [2], [3]]
deepArray; // WARNING: [[9], [2], [3]]

Merging Arrays

1
2
3
4
const lowNumbers = [ 1, 2, 3];
const highNumbers = [4, 5, 6];
const merged = [ ...lowNumbers, ...highNumbers];
merged; // [1, 2, 3, 4, 5, 6];

Spreading over function

1
2
3
const lowNumbers = [ 1, 2, 3];
function myFunction(x, y, z) { console.log(`${x}, ${y}, ${z}`); };
myFunction(...lowNumbers); // 1, 2, 3

Keep an extra eye out on that caveat, we’re not deep copying arrays when spreading.

Object Spread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const volvo = {
    make: 'Volvo',
    model: 'XC90',
    mileage: 2500,
    color: 'green'
};

const { make, model, ...restOfvolvo } = volvo;
make; // Volvo
model; // XC90
restOfvolvo; // { mileage: 2500, color: 'green' }
//const { ...restOfvolvoStart, make, model } = volvo; // Not allowed

// New variable names when destructuring objects
const { make : newMakeName, model : newModelName } = volvo;
newMakeName; // Volvo
newModelName; // XC90

Copying Objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const volvo = {
    make: 'Volvo',
    model: 'XC90',
    mileage: 2500,
    color: 'green'
};
const volvoCopy = { ... volvo };
volvoCopy; // { make: 'Volvo', model: 'XC90', mileage: 2500, color: 'green' }

// Caveats -> They objects are not "deep copied".
const audi = {
    make: 'Audi',
    engine: {
        type: 'diesel'
    },
    color: 'navy'
};
const notDeepCopyObject = { ...volvo, ...audi };
audi.engine.type = 'petrol'; // WARNING: No deep copy
audi.color = 'brown'; // OK
notDeepCopyObject; // {make: 'Audi', model: 'XC90', mileage: 2500, color: 'navy', engine: { type: 'petrol' }}

Merging Objects

1
2
3
4
5
6
7
8
9
10
11
12
const volvo = {
    make: 'Volvo',
    model: 'XC90',
    mileage: 2500,
    color: 'green'
};
const bmw = {
    make: 'bmw',
    color: 'blue'
};
const hybrid = { ...volvo, ...bmw};
hybrid; //{ make: 'bmw', model: 'XC90', mileage: 2500, color: 'blue'}

Bonus: Spreading Args in Function

1
2
3
4
5
// Spreading args in function
function moreArgs(a, b, ...multiple) {
    console.log(multiple.map(arg => arg));
}
moreArgs('a', 'b', 'c', 'd', 'e', 'f'); // ['c', 'd', 'e', 'f']

Compatibility

As you can see at this compatibility-table, we still don’t have full support. But here’s babel to the rescue. Just add the following plugin to your project and .babelrc.

1
2
3
4
5
6
npm install --save-dev babel-plugin-transform-object-rest-spread

// And then in your .babelrc
{
  "plugins": ["transform-object-rest-spread"]
}

That’s it!

I hope that this cheatsheet will help you when you will have to remember how to spread things in Javascript. Is there any other ways that you use the spread operator that I’ve missed? Feel free to comment or e-mail me @ tommy@snappyjs.com and I’ll make sure to add it to this list!

Please follow and like SnappyJS:

Leave a Reply

Your email address will not be published.