//

WEB APPLICATION SECURITY

ES6 introduced improved parameter handling in JavaScript. Instead of the half array arguments object, these new improvements will significantly improve how we handle arguments and parameters.

Spread Operator

In ES5 we had to pass in the context to a function with apply method.

var array = [2, 3, 5];
Math.min.apply(Math, array); // 2

ES6 introduced in the spread operator, which expands the array to create individual values for the function.

var array = [2, 3, 5];
Math.min(...array); // 2

Spread operator can also be used with other paramters, multiple times as well as mixed.

function func() {
  console.log(arguments);
}
 
const parameters = [3, 4, 8];
func(1, ...parameters, 11, ...[15, 20]);

Spread operator is also works well with constructors.

new Date(...[1980, 2, 15]);
// Sat Mar 15 1980 00:00:00 GMT+1000 (AEST)

Rest Parameters

Rest parameters somewhat does the opposite of the spread operator. It collects parameters and turns them into an array just like the arguments half array.

function func(...rest) {
  console.log(rest);
}
 
func('a', 'b', 1, 2);
// ["a", "b", 1, 2]

Rest parameters improve the readability of the code immensely.

Rest Limitations

Rest paramater has to be the last one and you can’t have more than one.

Default Parameters

ES6 now allows default parameters in the function signature.

function func(a = 1, b = 2) {
  console.log(a, b);
}
 
func(2); // 2 2
func(); // 1 2

Conclusion

ES6 parameter handling has come a long way since the last version. These improvements will make parameter handling in JavaScript a breeze.