Coming from Python and 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
JavaScript function parameters are defined as undefined by default. However, it may be useful to set a different default value. That is where default parameters come into play. Syntax: function name(parameter=value,...parameters) { }
Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.
The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
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());
Cause you need an object which can be deconstructed:
fun({})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With