DEV Community

Ayako yk
Ayako yk

Posted on

JavaScript Essentials: How Rest Parameters and Spread Syntax Work

In the previous blog post, I mentioned Spread Syntax, which was introduced in the ES6 specification. It allows developers to write simpler and cleaner code. There's another method that uses a similar syntax, ..., but it does the opposite. Today, I'll discuss Rest Parameters and Spread Syntax.

Rest Parameters
Rest parameters allow you to collect all remaining arguments into a single array.

Example

function example(num1, num2, ...args) {
    console.log(args); // [3, 4, 5]
}
example(1, 2, 3, 4, 5);
Enter fullscreen mode Exit fullscreen mode

Spread Syntax
Spread syntax allows an array or other iterable to be expanded into individual elements.

Example 1: "Expand" the iterable object into a list of arguments

function findMax(arr) {
    let maxNum = Math.max(...arr);
    console.log(maxNum); // 500
}
findMax([200, 100, 500]);
Enter fullscreen mode Exit fullscreen mode

Example 2: Merge multiple arrays

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arrCombined = [...arr1, ...arr2];
console.log(arrCombined); // [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

Spread syntax can also be used to copy arrays and objects because it works on iterable elements.
As I mentioned in a previous blog post, spread syntax operates similarly to a for..of loop, it processes each element of an array or object and copies it into a new array or object. This makes spread syntax a simpler alternative to methods like Object.assign({}, obj) for creating shallow copies.

Clone Example

let user = { name: "John", age: 30 }; 

let clone1 = Object.assign({}, user); 
console.log(clone1.name); // John 
console.log(clone1.age); // 30

let clone2 = {...user};
console.log(clone2.name); // John 
console.log(clone2.age); // 30
Enter fullscreen mode Exit fullscreen mode

Note: Shallow Copy Limitation
Spread syntax only creates a shallow copy, meaning it copies only the top-level properties of an object. If the object has nested objects, those nested objects are still referenced, not fully copied. For a deep copy, you can use modern methods like structuredClone.

Top comments (0)