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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay