8 ms·
"Optional Parameters and Default Values" Since JavaScript will still invoke a function call even if the number of arguments don't match up, parameter defaults
by nxn 15y ago
"Optional Parameters and Default Values"
Since JavaScript will still invoke a function call even if the number of arguments don't match up, parameter defaults will not completely eliminate all the problems he lists.
function(a = 1, b = "Smith", option = {}) { .. }
Will still break upon trying to invoke it without parameter 'b' since param 'option' will just take its place while option will become an empty object.
Furthermore he argues against "option = option || {};" only to do the same thing in the function header: "function(a, b, option = {}) { .. }"? What difference does that make?
The whole section in my opinion is negated by passing object literals to functions. Stuff like:
func({ a: 1, b: "Smith", option: { .. });
That makes it easy to read and easier to handle since names are agreed upon by both the caller and the function handling the invocation:
var opt = config.option || {};
This is a common practice in JavaScript already, and it beats the solutions he wished were added to the language.
- Groxx 15y agoI'm very much in agreement with objects-as-named-params. Default params just mitigate the problem, ambiguous function calling still rears its head as soon as you have multiple optional arguments of the same type. As to the "option = option || {}", he was referring to the ultimate "option = {}" assignment if you passed a falsy value (0, "", false), which is different than if you didn't pass a value (undefined). Which is resolved by "option = option === undefined ? option : {}", which is even larger and kinda ugly.
- nxn 15y agoAhh, I see. The thing is, I can't think of a single way to make {} be treated as false in the boolean context, so 1) I don't think you'd ever need anything more than "option = option || {}", 2) I think the example would have been better off using an integer or string where you actually might have to use the ugly long format. EDIT: Unless of course you get some non object value passed in and you want to be sure to keep it regardless of whether or not it is falsy. Not sure why you'd want to do that -- I am sure I would NOT like to see someone do that if I had to deal with their code.
- bzbarsky 15y agoHis point is that if config.option is supposed to be an integer, not an object, then your proposed syntax falls down when trying to determine whether 0 was passed or whether nothing was passed.