Embracing Rest/Spread Operators in JavaScript (ES6)

Kevin Diesenberg
2 min readJun 8, 2023

One of the most useful additions in ECMAScript 6 (ES6) is the rest/spread operator (...). It has made working with arrays and objects in JavaScript easier and more efficient. This post explores the rest and spread operators in detail, and provides examples of their utility.

Rest Operator

The rest operator allows you to represent an indefinite number of arguments as an array.

Here is an example of how you might use it in a function:

function sum(...args) {
return args.reduce((total, current) => total + current, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

The rest parameter (...args) is an array containing all arguments passed to the function.

We can also use the rest operator to collect remaining elements during array restructuring:

const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

console.log(first, second); // 1 2
console.log(rest); // [3, 4, 5]

Spread Operator

While the rest operator collects items together into an array, the spread operator does the opposite - it "spreads" the elements of an array (or any iterable) out.

Here's how you can use it to combine arrays:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

console.log(combined); // [1, 2, 3, 4, 5, 6]

The spread operator can also be used to spread the elements of an object. This can be useful for creating a copy of an object with some changes:

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };

console.log(obj2); // { a: 1, b: 2, c: 3 }

Conclusion

The rest and spread operators have brought a lot of flexibility and clarity to JavaScript. They can help simplify your code, making it more readable and maintainable. In the next post, we will explore the concept of default parameters in ES6, another handy feature to handle function arguments. Stay tuned!

--

--

Kevin Diesenberg

Software Engineer | JavaScript | React | Ruby | Rails | SQL | Skydiver | Outdoor Enthusiast | Paramotor Pilot | Cyclist | Edible Mushroom Hunter