feat(curriculum): Add interactive examples to What is the arguments Object (#63376)

This commit is contained in:
Clarence Bakosi 2025-10-31 20:24:49 +01:00 committed by GitHub
parent db86461ef2
commit 011dcb04b7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-the-arguments-object
---
# --description--
# --interactive--
As you recall from earlier lessons and workshops, you can create functions with a number of parameters and call that function with arguments.
@ -23,6 +23,8 @@ getSum(3, 4); // 7
But what if you have a function that is called with more arguments than it was defined to accept?
:::interactive_editor
```js
// function definition
function getSum(num1, num2) {
@ -33,12 +35,16 @@ function getSum(num1, num2) {
console.log(getSum(3, 4, 5)); // 7
```
:::
JavaScript will not throw an error in this case. It will instead ignore the extra argument and just add the numbers `3` and `4` together. Functions that accept a variable number of arguments are known as <dfn>variadic functions</dfn>.
If you are working with variadic functions, then you can utilize the `arguments` object. This array-like object contains the values of the arguments passed into the function.
Here is an example:
:::interactive_editor
```js
function logArgs() {
for (const arg of arguments) {
@ -55,8 +61,12 @@ logArgs(1, 2, 3);
logArgs("example"); // "example"
```
:::
Since the `arguments` object is array-like, you can access an argument at a specific index like this:
:::interactive_editor
```js
function getArg() {
return arguments[1];
@ -65,8 +75,12 @@ function getArg() {
console.log(getArg(2, 4, 6)); // 4
```
:::
You can also use the `length` property like this to get the number of arguments the function was called with:
:::interactive_editor
```js
function getArgs() {
return arguments.length;
@ -76,8 +90,12 @@ console.log(getArgs("Example")); // 1
console.log(getArgs("Another", "Example")); // 2
```
:::
Even though the `arguments` object appears to act like a real array, it does not have built in `Array` methods like `includes` or `push`. To have access to those methods, you would need to first convert the `arguments` object to a real array using something like `slice`, `Array.from()` or the spread operator:
:::interactive_editor
```js
function hasCat() {
return [...arguments].includes("cat");
@ -87,6 +105,8 @@ console.log(hasCat("dog", "chicken", "cat")); // true
console.log(hasCat("dog", "chicken", "horse")); // false
```
:::
While it is possible to work with the `arguments` object for variadic functions, modern JavaScript applications will normally use rest parameter syntax. You will learn more about that in a future lesson.
# --questions--