Suppose you have a palette of color names in an array and you want to create a new palette with some extra colors. You write this code:
const oldPalette = ['plum', 'orchid'];
const newPalette = oldPalette;
newPalette.push('linen');
newPalette.push('thistle');
Try running this code in your browser's console. Does newPalette
contain the colors you expect? Does oldPalette
?
The variable newPalette
is an alias that points to the same array as oldPalette
. Changes made through one of the variables will alter the single shared array that's in memory. What if you wanted newPalette
to point to a different array? There's no clone
method for arrays, but you could write this code:
const oldPalette = ['plum', 'orchid'];
const newPalette = [];
for (let color of oldPalette) {
newPalette.push(color);
}
newPalette.push('linen');
newPalette.push('thistle');
Try running this code. Are the arrays distinct?
This second approach is written more compactly using JavaScript's spread syntax:
const oldPalette = ['plum', 'orchid'];
const newPalette = [...oldPalette];
newPalette.push('linen');
newPalette.push('thistle');
The expression ...oldPalette
expands to the elements of oldPalette
. This code can be shortened even more by bundling the new colors into the array literal:
const oldPalette = ['plum', 'orchid'];
const newPalette = [...oldPalette, 'linen', 'thistle'];
Objects are cloned in a similar manner:
const image = {
width: 500,
height: 300,
path: 'dog-playing-solitaire.png',
};
const accessibleImage = {
...image,
alt: 'A dog playing solitaire.',
};
The spread syntax only produces a shallow clone of the original array or object. The new collection is a separate structure, but any non-primitive values will be copied to the new structure as aliases.