Rest and Spread Operators

 Rest and Spread Operators


The rest and spread operators provide convenient ways to work with arrays and objects.


// Rest Operator

function sum(...numbers) {

  return numbers.reduce((acc, num) => acc + num, 0);

}


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


// Spread Operator

const arr1 = [1, 2, 3];

const arr2 = [4, 5, 6];

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


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

In the example above, the rest operator (...) is used in the sum function to collect multiple arguments into an array. The spread operator (...) is used to spread the elements of arr1 and arr2 into the combined array.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...