feat(curriculum): Add interactive examples to rest parameters lesson (#63385)

This commit is contained in:
Giftea ☕
2025-10-31 20:32:27 +01:00
committed by GitHub
parent 962aa57133
commit c09b40797c

View File

@@ -5,10 +5,12 @@ challengeType: 19
dashedName: what-are-rest-parameters-and-how-do-they-differ-from-the-arguments-object
---
# --description--
# --interactive--
In the previous lesson, you learned how to work with the `arguments` object which is an array-like object containing the values of the arguments passed into the function.
:::interactive_editor
```js
function logArgs() {
for (const arg of arguments) {
@@ -23,10 +25,14 @@ logArgs(1, 2, 3);
// 3
```
:::
While this is a valid way to access and work with a variable set of arguments from a function, modern JavaScript applications will use the rest parameter syntax instead.
Here is an updated example using the rest parameter syntax instead of the `arguments` object:
:::interactive_editor
```js
function logArgs(...args) {
for (const arg of args) {
@@ -41,6 +47,8 @@ logArgs(1, 2, 3);
// 3
```
:::
This updated example no longer references the `arguments` object directly. Instead, the function definition's last parameter has three dots in front of it. This causes this rest parameter to be placed within an `Array` object. You can name this rest parameter whatever you like. Just make sure it is the last parameter in the function definition like this:
```js
@@ -59,7 +67,7 @@ There are a few more restrictions when dealing with the rest parameter syntax. O
// Won't work
function badFunction(...args, ...moreArgs) {
// some code here
// some code here
}
```
@@ -69,7 +77,7 @@ Another restriction is that the rest parameter cannot have a default value. Othe
```js
function badFunction(...args = [1,2]){
// some code here
// some code here
}
```
@@ -77,6 +85,8 @@ So what are some differences between the `arguments` object and `rest` parameter
One key difference is that the `arguments` object is not a real array so it doesn't support methods like `includes`, `pop` and `push`. But the rest parameter is an `Array` instance. So you can use valid built in array methods without needing to convert it to a real array first.
:::interactive_editor
```js
function hasCat(...args) {
return args.includes("cat");
@@ -86,6 +96,8 @@ console.log(hasCat("dog", "chicken", "cat")); // true
console.log(hasCat("dog", "chicken", "horse")); // false
```
:::
# --questions--
## --text--