ES6 has a few new features when it comes to working with parameters. To get these examples working, you most likely will have to use Firefox.
Pluto Hearts ES 6 Features |
Default Parameters
Allowing for
default parameters is a new feature being added into ES6,
and are really simple to use. When
defining a function & specifying the parameters just add an equal sign and the value and you want to default it to and BAM! DONE! So you would write your function like this:
function defaultParam(foo = "bar"){};
Now if the first parameter passed for foo is
undefined then it will default to "bar".
However if it is null then it will be passed in as null! Note that you can actually explicitly send in
undefined it WILL use the default value. You can also call functions to get the
default value for a parameter, but be aware that the function will NOT be called unless undefined is passed
in for that parameter.
Rest Operator
The rest operator “…”is used when you define a function and
works similarly to something like ‘varargs’ in Java or the ‘params’ in c#. If placed before the last parameter in a
function definition it turns it into an array and places all arguments that
aren’t accounted for into the array. You would write your function like this:
function restParam(foo, ...bar ){}; // bar is now an array
Spread Operator
The spread operator "..." is the same as the rest operator syntax wise, but used differently. While the rest operator brings parameters together, the spread operator blasts arrays apart.
So the spread operator can be used to “spread”
and array into individual arguments for a function call, or it can be used to
“spread” an array out for use in another array definition. It would be used like this:
function spreadParam(foo, bar){}; spreadParam(...["foo","bar"]);
One thing to note is that also works on strings as well.
Cheers!