Rest & Spread Operators

Rest & Spread Operators

·

2 min read

The "rest" operator (also known as the "spread" operator) is a feature in JavaScript that allows you to easily manipulate arrays and objects. It was introduced in ECMAScript 6 and is represented by three dots (...).

The rest operator is used to gather all remaining elements in an array into a new one. For example, you can use the rest operator to extract all elements from an array except for the first one:

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

//example 2
function sum(name, ...args) {     //rest operator will take all remaning arguments
    let sum = 0;
    for (const key in args) {
     sum += args[key];
    }
    console.log(sum)
    console.log(name)
}
sum("ashish",9,8,7,6)

The spread operator works similarly, but instead of creating a new array, it spreads the elements of an array into a new one. For example, you can use the spread operator to merge two arrays:

const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const allNumbers = [...numbers1, ...numbers2];
console.log(allNumbers); // [1, 2, 3, 4, 5, 6]

//e.g. 2

let arr=[10,20,30,40]
function sum(...rest) {     //rest operator will take all remaning arguments
    let sum = 0;
    for (const key in rest) {
     sum += rest[key];
    }
    console.log(sum)
}
sum(...arr);  //here if you pass direct array then array is passed as single argument so we need to spread that 
console.log(...arr)           //array using spread operator

The rest operator and the spread operator are also useful when working with objects. The rest operator can be used to extract a certain properties from an object and the spread operator can be used to merge two objects.

const person = {
    name: 'John',
    age: 30,
    location: 'New York'
};

const { name, ...otherDetails } = person;
console.log(name); // 'John'
console.log(otherDetails); // { age: 30, location: 'New York' }
const person1 = {
    name: 'John',
    age: 30
};

const person2 = {
    location: 'New York'
};

const mergedPerson = { ...person1, ...person2 };
console.log(mergedPerson); // { name: 'John', age: 30, location: 'New York' }

In conclusion, the rest operator and spread operator are powerful features in JavaScript that allow you to easily manipulate arrays and objects. Whether you are extracting elements from an array or merging objects, these operators can make your code more concise and readable.