Extended parameter handling in ES6

In this article we will cover three new features which give us extended parameter handling.

First one is Default. It’s a simple and little addition that makes it much easier to handle function parameters.  Functions in JavaScript allow any number of parameters to be passed regardless of the number of declared parameters in the function definition. You probably know commonly seen the pattern in current JavaScript code:

Functions in JavaScript allow any number of parameters to be passed regardless of the number of declared parameters in the function definition. You probably know commonly seen the pattern in current JavaScript code:

 

 

As far as we know logical OR operator (||) always returns the second operand when the first is false. ES6 gives us a way to set default function parameters. Any parameters with a default value are considered to be optional.  So the example above can be written as follows.

You can even execute a function which returns some value as default parameter. So it’s not restricted to primitive values.

The second one is Rest   Let’s rewrite sayHelloTo function to handle all arguments passed to it (without validation — just for simplicity). If we want to use ES5, we probably also want to use arguments object.

But it’s not obvious that the function is capable of handling any parameters.  We have to scan a body of the function and find arguments object. ES6 introduces rest parameters to help us with this and other pitfalls. Rest parameters are indicated by three dots (…) preceding a parameter. Named parameter becomes an array which contain the rest of the parameters.  So our example can be changed as follows.

The last one is Spread The spread is closely related to rest parameters, because of three dots notation.  It allows to split an array to single arguments which are passed to the function as separate arguments. In ES6 when we want to pass an array to function as arguments list we use apply function.

Spread feature helps us to avoid this. Here is how it will look like with spread.

  • Topics:
  • JavaScript

Top Stories

High Five! You just read 2 awesome articles, in row. You may want to subscribe to our blog newsletter for new blog posts.