JavaScript and TypeScript course ยท Module 2: Functions, Arrays and Objects
Spread and Rest Operators
In this lesson6
In Jurassic Park we constantly combine data from different monitoring systems, copy sets of parameters and handle functions that receive two samples one day and ten the next. The spread (...) and rest (...) operators use the same notation, three dots, but play two opposite roles. Spread "unpacks" elements, while rest "packs" them into a single structure. "It is the park's transport system," says Dr. Rex. "Spread unloads sample containers onto separate workstations, and rest packs many samples into one container."
Spread Operator for Arrays
Spread "spreads" array elements into a place where individual values are expected. This is how you merge the list of carnivores with the list of herbivores:
const carnivores = ['T-Rex', 'Velociraptor', 'Spinosaurus'];
const herbivores = ['Triceratops', 'Brachiosaurus', 'Stegosaurus'];
// Merging arrays
const allDinos = [...carnivores, ...herbivores];
console.log(allDinos);
// ['T-Rex', 'Velociraptor', 'Spinosaurus', 'Triceratops', 'Brachiosaurus', 'Stegosaurus']
// Adding elements while merging
const withNew = ['Pteranodon', ...carnivores, 'Dilophosaurus'];
console.log(withNew);
// ['Pteranodon', 'T-Rex', 'Velociraptor', 'Spinosaurus', 'Dilophosaurus']The result is a single flat array, not an array of arrays, because spread inserts the elements rather than whole arrays. Writing [carnivores, herbivores] without the dots would give two nested containers. Both source arrays stay unchanged.
Copying an Array (Shallow Copy)
Spread creates a shallow copy of an array, a new array with the same elements. The syntax is const copy = [...original]:
const originalZones = ['A', 'B', 'C'];
const zonesCopy = [...originalZones];
zonesCopy.push('D');
console.log(originalZones); // ['A', 'B', 'C'] - original unchanged!
console.log(zonesCopy); // ['A', 'B', 'C', 'D']Warning - shallow copy! If the array contains objects, only the references to them are copied, not the objects themselves:
const dinos = [{ name: 'Rex', health: 100 }];
const dinosCopy = [...dinos];
dinosCopy[0].health = 50;
console.log(dinos[0].health); // 50 - the original changed too!
// Because both elements point to the same object in memoryOnly the outer container is new, while the nested objects still share references with the original. When you need an independent, deep copy, I recommend the built-in structuredClone() function.
Spread with Functions
Spread also lets you "unpack" an array into the arguments of a function that expects separate values, such as Math.max:
const temperatures = [36.5, 37.2, 38.1, 35.8, 39.0];
// Instead of Math.max(36.5, 37.2, 38.1, 35.8, 39.0)
const maxTemp = Math.max(...temperatures);
const minTemp = Math.min(...temperatures);
console.log('Max:', maxTemp); // 39
console.log('Min:', minTemp); // 35.8Without the dots, Math.max(temperatures) would receive a single array and return NaN. The console prints 39, not 39.0, because numbers do not store trailing zeros. Spread works on any iterable value, so [...'DNA'] gives ['D', 'N', 'A'].
Spread Operator for Objects
Spread also works with objects and "unpacks" key-value pairs into a new object:
const baseDino = { species: 'Unknown', health: 100, zone: 'X' };
// Copying an object
const dinoCopy = { ...baseDino };
console.log(dinoCopy); // { species: 'Unknown', health: 100, zone: 'X' }
// Overriding properties (the last one wins!)
const rex = { ...baseDino, species: 'T-Rex', zone: 'A' };
console.log(rex); // { species: 'T-Rex', health: 100, zone: 'A' }
// Merging objects
const position = { lat: 12.34, lon: 56.78 };
const status = { health: 85, alert: false };
const fullReport = { ...position, ...status, timestamp: Date.now() };
console.log(fullReport);
// { lat: 12.34, lon: 56.78, health: 85, alert: false, timestamp: ... }Spread copies an object's own enumerable properties, including those whose key is a Symbol. baseDino remains a template from which you can create more specimens.
Order Matters
When merging objects, later properties override earlier ones. That is why you always unpack the defaults first:
const defaults = { voltage: 10000, locked: true, zone: 'A' };
const userSettings = { voltage: 15000, zone: 'B' };
// Defaults first, then override
const config = { ...defaults, ...userSettings };
console.log(config);
// { voltage: 15000, locked: true, zone: 'B' }
// Reversed order - the defaults would override the settings!
const wrong = { ...userSettings, ...defaults };
console.log(wrong);
// { voltage: 10000, zone: 'A', locked: true } - wrong!A key's position is set by its first appearance, and its value by the last one. That is why the keys in wrong come in a different order and the default values won. In the same way, { ...{ a: 1, b: 2 }, ...{ b: 3, c: 4 } } gives { a: 1, b: 3, c: 4 }.
Rest Operator in Functions
Rest (...) in function parameters collects all remaining arguments into an array. An observer can report any number of species:
// Rest parameter - collects a variable number of arguments
function logSighting(observer, ...dinosaurs) {
console.log(`${observer} observed: ${dinosaurs.join(', ')}`);
console.log(`Species count: ${dinosaurs.length}`);
}
logSighting('Dr. Rex', 'T-Rex', 'Velociraptor', 'Triceratops');
// "Dr. Rex observed: T-Rex, Velociraptor, Triceratops"
// "Species count: 3"
logSighting('Dr. Rex', 'Brachio');
// "Dr. Rex observed: Brachio"
// "Species count: 1"The first argument goes to observer, and everything else goes to a real array dinosaurs, so join and length work on it. The older arguments object is not an array, which is why I recommend rest in new code.
Rest Must Be the Last Parameter
Rest collects everything that is left, so it has to come at the end of the parameter list. Otherwise JavaScript would not know where to stop collecting:
// Correct - rest at the end
function feedDinos(keeper, time, ...dinoNames) {
dinoNames.forEach(name => {
console.log(`${keeper} feeds ${name} at ${time}`);
});
}
feedDinos('Alan', '08:00', 'Rex', 'Blue', 'Delta');
// Error! Rest cannot come before other parameters
// function wrong(...names, time) {} // SyntaxError!A function can have only one rest parameter, and it is always the last one. Any other position ends with a SyntaxError before the code even runs.
Rest in Destructuring
Rest also works in array and object destructuring, which you know from the previous lesson:
// Rest in array destructuring
const rankings = ['T-Rex', 'Velociraptor', 'Spinosaurus', 'Giganotosaurus'];
const [champion, runnerUp, ...others] = rankings;
console.log(champion); // "T-Rex"
console.log(runnerUp); // "Velociraptor"
console.log(others); // ["Spinosaurus", "Giganotosaurus"]
// Rest in object destructuring
const sensor = { id: 'S-001', value: 42, unit: 'C', zone: 'A', active: true };
const { id: sensorId, value: sensorValue, ...metadata } = sensor;
console.log(sensorId); // "S-001"
console.log(sensorValue); // 42
console.log(metadata); // { unit: 'C', zone: 'A', active: true }In both cases rest creates a new array or a new object with everything that was not named.
Practical Patterns
Removing Properties from an Object
Combining destructuring with rest lets you leave out fields without modifying the object, for example to hide internal data before sending a report:
const dino = { name: 'Rex', _secret: 'code', health: 100, _internal: true };
// Pull out what you want to remove, the rest stays
const { _secret, _internal, ...publicData } = dino;
console.log(publicData); // { name: 'Rex', health: 100 }The dino object still has _secret. The extracted fields became separate variables, and publicData is a new object without them.
Creating a Copy with Modifications
Spread is also great for updating data. Instead of changing the original, you create a new version of it with overridden fields:
function updateDino(dino, updates) {
return { ...dino, ...updates, lastModified: Date.now() };
}
const rex = { name: 'Rex', health: 100, zone: 'A' };
const updatedRex = updateDino(rex, { health: 85, zone: 'B' });
console.log(updatedRex);
// { name: 'Rex', health: 85, zone: 'B', lastModified: ... }
console.log(rex.health); // 100 - original unchanged!The old record stays untouched, so it is easy to compare the state before and after the change. State updates in React and Redux are built on this pattern.
Practice
The sandbox contains array merging, copies, Math.max with spread, the order of merging objects and rest in functions. Swap the order of the spreads and check which value wins.
Code for this lesson: index.js
// === SPREAD AND REST OPERATORS ===
// 1. Spread - combining arrays
const carnivores = ['T-Rex', 'Velociraptor', 'Spinosaurus'];
const herbivores = ['Triceratops', 'Brachiosaurus'];
const allDinos = [...carnivores, ...herbivores];
console.log('=== Spread arrays ===');
console.log('All:', allDinos);
// 2. Copying array (shallow copy)
const original = ['A', 'B', 'C'];
const copy = [...original];
copy.push('D');
console.log('\n=== Copying ===');
console.log('Original:', original);
console.log('Copy:', copy);
// 3. Spread with functions
const temps = [36.5, 37.2, 38.1, 35.8, 39.0];
console.log('\n=== Spread with functions ===');
console.log('Max temp:', Math.max(...temps));
console.log('Min temp:', Math.min(...temps));
// 4. Spread for objects
const baseDino = { species: 'Unknown', health: 100 };
const rex = { ...baseDino, species: 'T-Rex', zone: 'A' };
console.log('\n=== Spread objects ===');
console.log('Rex:', JSON.stringify(rex));
// Combining objects
const position = { lat: 12.34, lon: 56.78 };
const status = { health: 85, alert: false };
const fullReport = { ...position, ...status };
console.log('Report:', JSON.stringify(fullReport));
// 5. Order matters
const defaults = { voltage: 10000, locked: true };
const settings = { voltage: 15000 };
console.log('\n=== Order ===');
console.log('Correct:', JSON.stringify({ ...defaults, ...settings }));
console.log('Bad:', JSON.stringify({ ...settings, ...defaults }));
// 6. Rest in functions
function logSighting(observer, ...dinosaurs) {
console.log(observer + ' sees: ' + dinosaurs.join(', '));
console.log('Count: ' + dinosaurs.length);
}
console.log('\n=== Rest in functions ===');
logSighting('Dr. Rex', 'T-Rex', 'Velociraptor', 'Triceratops');
// 7. Rest in destructuring
const [champion, runnerUp, ...others] = ['T-Rex', 'Raptor', 'Spino', 'Giga'];
console.log('\n=== Rest in destructuring ===');
console.log('Champion:', champion);
console.log('Rest:', others);
const { name, ...dinoStats } = { name: 'Rex', weight: 8000, zone: 'A' };
console.log('Name:', name);
console.log('Stats:', JSON.stringify(dinoStats));Remember: the same three dots on the right-hand side unload a container, while in parameters and on the left of an assignment they pack samples into a new one.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What will [...['A', 'B'], ...['C', 'D']] return?
2. What will { ...{ a: 1, b: 2 }, ...{ b: 3, c: 4 } } return?
3. Where must the rest parameter (...args) be in the function parameter list?
4. Why does spread create a 'shallow copy' of objects?
Hands-on tasks in the game
- Code editor
You have the arrays const carnivores = ['T-Rex', 'Velociraptor'] and const herbivores = ['Triceratops'] and the object const defaults = { zone: 'A', locked: true }. Using the spread operator, create: allDinos (both arrays merged), carnivoresCopy (a new copy of carnivores) and config (defaults overridden with zone: 'B'). Also write a function countSightings(observer, ...dinos) that returns the number of dinosaurs passed.
- Horizontal ordering
Arrange the elements of creating an array copy using spread:
- Code editor
You have an object const dino = { name: 'Rex', health: 100, _secret: 'code', _internal: true }. Using destructuring with the rest operator, create a new object publicData without the _secret and _internal fields (dino must stay unchanged). Write a function updateDino(dino, updates) that returns a new object: a copy of dino overridden with the fields from updates, without changing the object passed in.
- Code editor
Create two DNA sample identifiers: const sampleId1 = Symbol('DNA-001') and const sampleId2 = Symbol('DNA-001'). Display the result of sampleId1 === sampleId2 in the console. Then create an object specimen with the property name: 'T-Rex' and the sample data (e.g. { purity: 98.5 }) stored under the key sampleId1.
Tasks after this lesson
- QuestionSpread - Merging Arrays
- QuestionSpread - Overriding Object Properties
- Coding taskPractice: Spread and Rest - Arrays and Objects
- Put in orderSpread - Copying an Array
- QuestionRest - Function Parameters
- QuestionSpread - Shallow Copy
- Coding taskPractice: Advanced Spread and Rest Patterns
- Coding taskUsing the Symbol Type