CHAPTER 5
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 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:
Code Listing: 79
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:
Code Listing: 80
hello world hey world |
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.
Code Listing: 81
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:
Code Listing: 82
["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.
The spread operator is like the reverse of rest parameters. It allows you to expand an array into multiple formal parameters.
Code Listing: 83
function add(a, b) { return a + b; } let nums = [5, 4]; console.log(add(...nums)); |
Running the preceding code produces the following result:
Code Listing: 84
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:
Code Listing: 85
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:
Code Listing: 86
9 |
Let’s look at one more example when creating array literals:
Code Listing: 87
let a = [2, 3, 4]; let b = [1, ...a, 5]; console.log(b); |
Running the preceding code produces the following output:
Code Listing: 88
[1, 2, 3, 4, 5] |
As you can see, you can get very creative with the usage of the spread operator!