-1

What is Spread Syntax and Rest Parameters? Are they related to each other?

I read about both but, I couldn't fully understand there use and purpose.

Any help would be much appreciated!

RamenChef
  • 5,557
  • 11
  • 31
  • 43
skm
  • 1,192
  • 1
  • 11
  • 23
  • 1
    https://stackoverflow.com/questions/20541339/usage-of-rest-parameter-and-spread-operator-in-javascript – Bergi Sep 27 '17 at 19:39
  • https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper?noredirect=1&lq=1 – Bergi Sep 27 '17 at 19:40
  • To me it makes more sense to close this question as a ***duplicate*** of [Usage of rest parameter and spread operator in javascript](https://stackoverflow.com/q/20541339) rather than closing it as "too broad" (or whatever the correct term is). – Henke Mar 14 '21 at 13:09

1 Answers1

1

Spread syntax and Rest Parameters

I strongly recommend taking a look at the documentation, as it is very comprehensive and informative.

Spread Syntax

Spread syntax allows an iterable such as an array expression to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Example:

const array1 = [0, 1, 2, 3];
const array2 = [...array1, 4, 5, 6];

// array2 = [0, 1, 2, 3, 4, 5, 6,]

// Iterates over all properties of the specified object, adding it to the new object
// let objClone = { ...obj };

Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Example:

function fun1(...theArgs) {
    console.log(theArgs.length);
}

fun1();  // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
Wolfie
  • 1,369
  • 8
  • 16