DEV Community

loading...

Predefined parameters can be default value for next ones

beatrizrezener profile image Beatriz Rezener ・1 min read

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]
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 ;)']

Discussion

pic
Editor guide