What does the spread operator (...) do in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
... expands an array or object in place, so its items or properties are copied into a new array, a new object or a function call's arguments. The copy is shallow: nested objects are shared, not copied.This answer is one piece of Chapter 4: Arrays and Objects.
Test data is usually a base object with one or two fields changed per test. Spread is the short way to write that without touching the base.
In the example, { ...baseOrder, status: 'packed', qty: 3 } copies every property of baseOrder into a new object, then overrides two of them. When the same name appears twice, the later value wins, so order matters: put the overrides after the spread. baseOrder.status is still pending afterwards.
Arrays work the same way. [...brewing, ...grinding] joins two SKU lists into one new array. Spread also turns an array into separate arguments, which is why Math.max(...prices) finds the highest price.
The last lines are the trap. Spread copies one level deep. copy.address is not a new object; it is the same address object withAddress holds. Changing copy.address.city to Pune changes the original too. When two tests share a fixture with nested data, that is how one test quietly changes the other's data. Use structuredClone() when you need a deep, independent copy.
const baseOrder = { city: 'Kochi', status: 'pending', qty: 1 };
const packed = { ...baseOrder, status: 'packed', qty: 3 };
console.log(packed);
console.log(baseOrder.status);
const brewing = ['MRD-1001', 'MRD-1002'];
const grinding = ['MRD-1003', 'MRD-1004'];
console.log([...brewing, ...grinding]);
console.log(Math.max(...[4290, 6490, 11900]));
const withAddress = { id: 'ORD-4100', address: { city: 'Kochi' } };
const copy = { ...withAddress };
copy.address.city = 'Pune';
console.log(withAddress.address.city);{ city: 'Kochi', status: 'packed', qty: 3 }
pending
[ 'MRD-1001', 'MRD-1002', 'MRD-1003', 'MRD-1004' ]
11900
Puneb.qty after const a = { qty: 1, city: 'Kochi' } and const b = { qty: 5, ...a }?Try a real drill. No sign-up.
Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free