java-script:rest-vs-spread-operator
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| java-script:rest-vs-spread-operator [2023/08/10 12:55] – odefta | java-script:rest-vs-spread-operator [2025/01/02 18:22] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 11: | Line 11: | ||
| ===== Rest operator (...) ===== | ===== Rest operator (...) ===== | ||
| - | The rest operator is used to **collect all remaining iterable elements into an array**. This can be particularly useful in function signatures. \\ | + | The rest operator is used to **collect all remaining iterable elements into an array or object**. |
| + | |||
| + | ==== Usage in function arguments ==== | ||
| + | |||
| + | This can be particularly useful in function signatures. \\ | ||
| Example: | Example: | ||
| Line 35: | Line 39: | ||
| A function cannot have multiple rest parameters. | A function cannot have multiple rest parameters. | ||
| </ | </ | ||
| + | |||
| + | ==== Destructuring Arrays ==== | ||
| + | |||
| + | You can use the rest operator to collect the rest of the elements into an array when destructuring: | ||
| + | |||
| + | <code javascript> | ||
| + | const [first, second, ...rest] = [1, 2, 3, 4, 5]; | ||
| + | console.log(rest); | ||
| + | </ | ||
| + | |||
| + | ==== Destructuring Objects ==== | ||
| + | |||
| + | Similarly, when destructuring objects, the rest operator can collect the remaining own enumerable property keys into a new object: | ||
| + | |||
| + | <code javascript> | ||
| + | const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4}; | ||
| + | console.log(rest); | ||
| + | </ | ||
| + | |||
| + | ==== Clone Objects and Arrays ==== | ||
| + | |||
| + | It's a handy way to create a shallow copy of an object or an array. | ||
| + | |||
| + | <code javascript> | ||
| + | const obj = {a: 1, b: 2}; | ||
| + | const clonedObj = {...obj}; // Output: {a: 1, b: 2} | ||
| + | </ | ||
| ===== Spread operator (...) ===== | ===== Spread operator (...) ===== | ||
java-script/rest-vs-spread-operator.1691672107.txt.gz · Last modified: (external edit)
