DEV Community

Beatriz R
Beatriz R

Posted on

Predefined parameters can be default value for next ones

JavaScript ES6 allow us to initialize named parameters with default values.

But cooler than that is knowing that we can use earlier defined parameters as default value for the next function parameters. Examples:

function createContainer(height = 180, width = height) {
    return [height, width]
}
createContainer() // [180, 180]
createContainer(300) // [300, 300]
createContainer(120, 240) // [120, 240]
Enter fullscreen mode Exit fullscreen mode
function greet(name, salute = 'Hello', message = `${salute}, ${name}!`) {
    return [name, salute, message];
}

console.log(greet('Beatriz')) 
// ['Beatriz', 'Hello', 'Hello, Beatriz!']

console.log(greet('Beatriz', 'Good Morning'))
// ['Beatriz', 'Good Morning', 'Good Morning, Beatriz!']

console.log(greet('Beatriz', 'Hi', 'Thank you ;)')) 
// ['Beatriz', 'Hi', 'Thank you ;)']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)