Extended Parameter Handling
Another nice set of features introduced in ES6 is the
extended parameter handling. These provide a very nice set of idioms that bring
us very close to languages like C# or Java.
Default parameter values and optional parameters
Default parameters allow your functions to have optional
arguments without needing to check arguments.length or check for undefined.
Let’s take a look at what that might look like:
let greet = (msg = 'hello', name = 'world') =>
{
console.log(msg,name);
}
greet();
greet('hey');
Looking at the preceding code, you can see that we are using
the new fat arrow (=>) syntax as well as the new let keyword. Neither of
those are necessary for this example, but I added it to give you more exposure
to the new syntax.
Running the preceding code produces the following result:
hello world
hey world
Rest parameter
Handling a function with a variable number of arguments is
always tricky in JavaScript. Rest parameters (…), indicated by three
consecutive dot characters, allow your functions to have a variable number of
arguments without using the arguments object. The rest parameter is an instance
of Array, so all array methods work.
function f(x, ...y) {
console.log(y);
// y is an
Array
return x *
y.length;
}
console.log(f(3, 'hello', true) === 6);
Running the preceding code produces the following result:
["hello", true]
true
You can have as many regular arguments as you’d like, but
the rest parameter must always be the last. This may be one of the new features
that seems a little foreign and weird, but over time you will find that this is
a very nice feature and will come in very handy.
Spread operator
The spread operator is like the reverse of rest parameters.
It allows you to expand an array into multiple formal parameters.
function add(a, b) {
return a +
b;
}
let nums = [5, 4];
console.log(add(...nums));
Running the preceding code produces the following result:
9
Again, this may seem strange, but once you start using both
of these you will find them useful.
Let’s change this slightly to have both a regular parameter
and a spread operator in the same call:
function add(a, b) {
return a +
b;
}
let nums = [4];
console.log(add(5, ...nums));
As with the previous example, we get the same result:
9
Let’s look at one more example when creating array literals:
let a = [2, 3, 4];
let b = [1, ...a, 5];
console.log(b);
Running the preceding code produces the following output:
[1,
2, 3, 4, 5]
As you can see, you can get very creative with the usage of
the spread operator!
Comments
Post a Comment