DEV Community

Sujith V S
Sujith V S

Posted on

Rest and Spread operator in JavaScript | ES6

Spread Operator
Spread operator helps us to copy all the elements inside array or objects. After copying those elements, we can add those elements to another array or objects.

Let's look at an example,
In Array:

const number = [1, 2, 3];
const newNumbers = [...number, 4];
console.log(newNumbers)

Output:
[ 1, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode

In Objects

const person = {
    name: 'Max'
}
const newPerson = {
    ...person,
    age: 26
}
console.log(newPerson)

Output:
{ name: 'Max', age: 26 }
Enter fullscreen mode Exit fullscreen mode

Three dots before the array name or object name is used to copy the elements inside that array or object. ...person...number

Rest Operator
Rest operator is used with functions.
It is used to merge a list of function arguments into an array. And we can perform array operations in it.

Let's look at an example,

const numberList = (...args) => {
    return args.filter(el => el === 1)
}

console.log(numberList(1, 2, 3))
Enter fullscreen mode Exit fullscreen mode

...args is the rest operator which is used as the function parameter.This rest operator takes up all the different arguments and merge them into an array.

Top comments (0)