Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 17, 2022 07:12 pm GMT

Rest vs Spread Operator

I remember being asked about the difference between the rest and spread operator and drawing a blank. I hadn't used the spread operator since I was in my bootcamp, and even on that occasion it seemed a bit glossed over.

So I wanted to address this knowledge gap by walking through the use and differences between the rest and spread operator.

It's easy to confuse the spread operator and the rest operator because their syntax is so similar.

Spread Operator: we can spread the content of an iterable into individual elements.

Note: An iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables

Let's look at the Spread Example:

const arr = ["My", "name", "is", "Melissa"]const copyArr = [...arr]console.log(copyArr)console.log(...copyArr)

Let's see what the console returns when we console.log(copyArr)

Spread operator returning the array of strings

We return ["My", "name", "is", "Melissa"]

The spread operator allows us unpack collected elements into their own single elements.

Rest: allows a function to accept an indefinite number of arguments as an array

Let's look at an example:

var myName = ["Robert", "Alfred", "Cole"] ;const [firstName , ...familyName] = myName ;console.log(firstName); console.log(familyName); 

The elements of myName is being broken apart and reorganized into a new subarray. This is called destructuring, an array or object is broken into smaller pieces.

Let's look at our console:

Rest example 1:  raw `console.log` endraw  of  raw `console.log(firstName)` endraw

The first console.log of console.log(firstName) returns the first element in the array, 'Robert'. The rest of the elements in the array are collected and put into a new sub array called familyName. This is why when we console.log(familyName) we get the new sub array consisting of the rest of the original array ["Alfred", "Cole"].

Rest example 2: console.log(familyName)

Think of rest as a mnemonic device that means it creates its own collection of the rest of the array. In this example, that would be the new sub array ["Alfred", "Cole"].

To further understand the logic at play, create your own examples and test them in your console of your choosing. Practicing this achieves a better understanding of rest and spread!


Original Link: https://dev.to/melguachun/rest-vs-spread-operator-1ne5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To