}
addPrefix
(
"con"
,
"verse"
,
"vex"
);
// ["converse", "convex"]
Note that if you use the spread operator in a function declaration, it must be the last
argument. If you put arguments after it, JavaScript wouldn’t have a reasonable way to
distinguish between what should go in the spread argument and what should go in
the remaining arguments.
In ES5, similar functionality can be accomplished with a special
variable that exists only within function bodies: arguments. This
variable was not actually an array, but an “array-like” object, which
often required special handling, or conversion to a proper array.
Spread arguments in ES6 address this weakness, and should be pre‐
ferred over using the arguments variable (which is still available).
Default Arguments
New in ES6 is the ability to specify default values for arguments. Normally, when val‐
ues for arguments aren’t provided, they get a value of
undefined
. Default values allow
you to specify some other default value:
function
f
(
a
,
b
=
"default"
,
c
=
3
) {
return
`
${
a
}
-
${
b
}
-
${
c
}
`
;
}
f
(
5
,
6
,
7
);
// "5 - 6 - 7"
f
(
5
,
6
);
// "5 - 6 - 3"
f
(
5
);
// "5 - default - 3"
f
();
// "undefined - default - 3"
Functions as Properties of Objects
When a function is a property of an object, it is often called a method to distinguish it
from a normal function (we’ll learn a more nuanced distinction between function and
method shortly). We already saw in
how we could add a function to an
existing object. We can also add a method in the object literal:
const
o
=
{
name
:
'Wallace'
,
// primitive property
bark
:
function
() {
return
'Woof!'
; },
// function property (method)
}
ES6 introduces a new shorthand syntax for methods. The following is functionally
equivalent to the preceding example:
Functions as Properties of Objects | 109