The implication of this is that you can call any function with any number of argu‐
ments. If you fail to provide arguments, they will implicitly receive the value
undefined
:
function
f
(
x
) {
return
`in f: x=
${
x
}
`
;
}
f
();
// "in f: x=undefined"
Later in this chapter, we’ll see how to handle the situation where you pass more argu‐
ments than the function defines.
Destructuring Arguments
Just as we can have destructured assignment (see
), we can have destruc‐
tured arguments (arguments are, after all, very much like variable definition). Con‐
sider destructuring an object into individual variables:
function
getSentence
({
subject
,
verb
,
object
}) {
return
`
${
subject
}
${
verb
}
${
object
}
`
;
}
const
o
=
{
subject
:
"I"
,
verb
:
"love"
,
object
:
"JavaScript"
,
};
getSentence
(
o
);
// "I love JavaScript"
As with destructuring assignment, property names must be identifier strings, and a
variable that doesn’t have a matching property in the incoming object will receive the
value
undefined
.
You can also destructure arrays:
function
getSentence
([
subject
,
verb
,
object
]) {
return
`
${
subject
}
${
verb
}
${
object
}
`
;
}
const
arr
=
[
"I"
,
"love"
,
"JavaScript"
];
getSentence
(
arr
);
// "I love JavaScript"
Finally, you can use the spread operator (
...
) to collect any additional arguments:
function
addPrefix
(
prefix
,
...
words
) {
// we will learn a better way to do this later!
const
prefixedWords
=
[];
for
(
let
i
=
0
;
i
<
words
.
length
;
i
++
) {
prefixedWords
[
i
]
=
prefix
+
words
[
i
];
}
return
prefixedWords
;
108 | Chapter 6: Functions