DEV Community

Sujith V S
Sujith V S

Posted on

2 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

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

Okay