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:

1
2
3
4
5
6
function greet(name = 'world') {
    console.log(`Hello, ${name}!`);
}

greet();            // Outputs: 'Hello, world!'
greet('Alice');     // Outputs: 'Hello, Alice!'

2. Rest Parameters:

The rest parameter syntax (...) allows you to represent an indefinite number of arguments as an array.

Example:

1
2
3
4
5
6
7
function printNumbers(...numbers) {
    for (let number of numbers) {
        console.log(number);
    }
}

printNumbers(1, 2, 3, 4, 5);  // Outputs: 1, 2, 3, 4, 5

3. Destructuring:

Destructuring allows you to unpack values from arrays, or properties from objects, into distinct variables.

Example:

1
2
3
4
5
6
function greet({name = 'world', age = 'unknown'} = {}) {
    console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet({name: 'Alice', age: 25});  // Outputs: 'Hello, Alice! You are 25 years old.'
greet();                          // Outputs: 'Hello, world! You are unknown years old.'

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.