Search code examples
javascriptecmascript-6named-parametersdefault-parameters

JavaScript (ES6): Named parameters and default values


I am coming from Python and am really liking the way to set named parameters and default values—now it seems that ES6 allows me to do similar. But I can't see why this last call breaks:

fun = ({first=1, last=1}) => (1*first+2*last)

console.log("-----------")

console.log( fun({first:1, last:2}) )

console.log("-----------")

console.log( fun({last:1, first:2}) )

console.log("-----------")

console.log( fun() ) // Breaks


Solution

  • You need a default object.

    var fun = ({ first = 1, last = 1 } = {}) => 1 * first + 2 * last;
    //                                 ^^^^
    
    console.log(fun({ first: 1, last: 2 }));
    console.log(fun({ last: 1, first: 2 }));
    console.log(fun());