ES6 Function Enhancements
Some ES6 features allow you to define default values for optional function parameters, to gather multiple arguments into an array using a rest parameter, and to destructure object and array arguments into function parameters.
ES6 (ES2015) introduced a number of useful features that enhance functions in JavaScript, including default parameter values, rest parameters, and destructuring.
1. Default Parameter Values:
In ES6, you can assign default values to function parameters. This means if no argument is provided for a parameter when the function is invoked, the parameter will use its default value.
Example:
|
|
2. Rest Parameters:
The rest parameter syntax (...
) allows you to represent an indefinite number of arguments as an array.
Example:
|
|
3. Destructuring:
Destructuring allows you to unpack values from arrays, or properties from objects, into distinct variables.
Example:
|
|
In this example, the function expects an object with properties name
and age
. If these are not provided, it uses default values. The empty object in the function parameters (= {}
) ensures the function won’t throw an error if it’s called without any arguments.
These features can greatly increase the readability and maintainability of your code. They’re a great demonstration of how JavaScript has evolved over the years to include more sophisticated language features.