Rest and Spread Operators in JavaScript

Rest and Spread Operators in JavaScript

Modern JavaScript introduces many features to simplify coding and improve efficiency. Two such powerful tools are the rest (...) and spread (...) operators. Although they look similar, they serve different purposes. Rest helps group values into an array, while spread splits or spreads values from an array or object.


This article explains:

  • What the rest and spread operators are.
  • How to use them with arrays, objects, and functions.
  • Practical examples for both beginners and advanced developers.


Rest Operator (...)

The rest operator collects multiple arguments or elements and bundles them into an array. It is commonly used in function arguments and destructuring.

Syntax:

function example(...rest) {
  console.log(rest); // Array of arguments
}         

1. Using Rest in Functions

When you don’t know how many arguments a function will receive, the rest operator helps.

Example: Summing Numbers

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

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

Here, ...numbers collects all arguments into an array, which is then processed by reduce.


2. Using Rest in Destructuring

The rest operator extracts remaining values from arrays or objects during destructuring.

Example: Array Destructuring and Object Destructuring

const user = { name: "Aarav", age: 25, city: "Delhi", country: "India" };

const { name, ...details } = user;

console.log(name); // Output: Aarav

console.log(details); // Output: { age: 25, city: "Delhi", country: "India" }        

The ...rest gathers the remaining properties into a new object.


Spread Operator (...)

The spread operator expands the contents of an array, object, or iterable into individual elements.

Syntax:

const newArray = [...existingArray];

const newObject = { ...existingObject };          


1. Using Spread with Arrays

The spread operator makes it easy to merge arrays or copy them without altering the original.

Example: Merging Arrays

const arr1 = [1, 2, 3];

const arr2 = [4, 5, 6];

const merged = [...arr1, ...arr2];

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


Example: Copying Arrays

const original = [1, 2, 3];

const copy = [...original];

copy.push(4);

console.log(original); // Output: [1, 2, 3]

console.log(copy); // Output: [1, 2, 3, 4]        


2. Using Spread with Objects

The spread operator simplifies copying or merging objects.

Example: Copying Objects

const user = { name: "Aarav", age: 25 };

const copy = { ...user };

copy.age = 30;

console.log(user); // Output: { name: "Aarav", age: 25 }

console.log(copy); // Output: { name: "Aarav", age: 30 }        

Example: Merging Objects

const obj1 = { name: "Aarav" };

const obj2 = { age: 25 };

const merged = { ...obj1, ...obj2 };

console.log(merged); // Output: { name: "Aarav", age: 25 }        


3. Using Spread in Functions

The spread operator can pass array elements as individual arguments to a function.

Example: Math.max

 const numbers = [1, 2, 3, 4, 5];

const max = Math.max(...numbers);

console.log(max); // Output: 5        

Here, ...numbers spreads the array into individual numbers, which Math.max processes.


Rest vs Spread: The Key Difference


Feature Rest (...)

  • Purpose Combines values into an array or object
  • Where Used Function arguments
  • Example function(...args)


Feature Spread (...)

  • Purpose Expands an array, object, or iterable
  • Where Used destructuring Arrays, objects, function calls
  • Example Math.max(...array)

Advanced Tips and Use Cases

1. Default Values with Rest:

You can set default parameters for rest arguments.

function greet(message, ...names) {
  console.log(`${message}, ${names.join(", ")}`);
}

greet("Hello", "Aarav", "Isha", "Rohan"); // Output: Hello, Aarav, Isha, Rohan        

2. Filtering Properties with Rest:

Remove specific properties from an object.

const user = { name: "Aarav", age: 25, city: "Delhi" };

const { age, ...rest } = user;

console.log(rest); // Output: { name: "Aarav", city: "Delhi" }        

3. Combining Rest and Spread:

Use both together for complex operations.

const arr = [1, 2, 3];

const newArr = [...arr, ...[4, 5]];

console.log(newArr); // Output: [1, 2, 3, 4, 5]        

Conclusion

The rest and spread operators make handling arrays, objects, and functions much easier in JavaScript. Whether you’re merging arrays, copying objects, or simplifying function arguments, these operators provide clean and efficient solutions.

要查看或添加评论,请登录

Sonu Tiwari的更多文章

社区洞察

其他会员也浏览了