DEV Community

Discussion on: Javascript: Spread Operators CheetSheet

Collapse
 
parenttobias profile image
Toby Parent

I tend to think of the spread operator as being on the right side of an assignment, and the rest operator as being on the left... but it can get foggy:

const capitalize = ([firstLetter, ...restOfWord])=>firstLetter.toUpperCase()+restOfWord.join('').toLowerCase();

console.log(capitalize("heLlO") ); // 'Hello'
Enter fullscreen mode Exit fullscreen mode

In this case, we're using the rest operator, but we're implicitly spreading the string into an array!

Collapse
 
msabir profile image
imsabir • Edited

Actually, Rest and Spread are part of one umbrella but working is Opposite to each ohter. In short:

The three dots in JavaScript are the spread / rest operator. The spread syntax allows an expression to be expanded in places where multiple arguments are expected.
The rest parameter syntax is used for functions with a variable number of arguments. The spread / rest operator for arrays was introduced in ES6

Rest Operator: collects all remaining elements or rest Item into an array.
When used in function arguments of a function declaration/expression it will convert
the remaining arguments into an array. This variant is called the Rest parameters
syntax.

function rest(first, second, ...remainder) {
  console.log(remainder);
}

// 30, 40 ,50 are the remaining parameters and will be 
// merged together in to an array called remainder 
rest(10, 20, 30, 40, 50);
Enter fullscreen mode Exit fullscreen mode

Will cover in deep in future blogs.

Cheers!!

Collapse
 
parenttobias profile image
Toby Parent

my own lazy understanding, rest happens on the assignment (left-hand) side, while spread happens on the evaluation (right-hand) side. Any time we're ... in an assigment to something (like a parameter), we're using rest.

Collapse
 
harshjoeyit profile image
Harshit Gangwar

Yes, I have the same understanding.

Collapse
 
mattthecuber profile image
MattTheCuber

That's such a clever one liner

Collapse
 
parenttobias profile image
Toby Parent

lol I love finding things that are elegant, clear, and concise. It says exactly what it's doing, from the parameter signature to the return. Makes me happy. :D