Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript (ES6): Named parameters and default values

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
like image 543
Norfeldt Avatar asked May 24 '18 14:05

Norfeldt


People also ask

What is default parameters in es6?

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) { }

What is default parameter JavaScript?

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.

Does JavaScript have named parameters?

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.

What is a parameter value in JavaScript?

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.


2 Answers

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());
like image 89
Nina Scholz Avatar answered Sep 22 '22 03:09

Nina Scholz


Cause you need an object which can be deconstructed:

fun({})
like image 38
Jonas Wilms Avatar answered Sep 23 '22 03:09

Jonas Wilms