I have defined a function like:
function call_api(url, callback, query = {}, body = {})
I expected a syntax where I can provide body and skip query:
call_api('/api/clients/new', function(x){console.log(x)}, body={1:2})
But I have to use this workaround:
call_api('/api/clients/new', function(x){console.log(x)}, {}, {1:2})
Even if I provide body=
, it appears its appearing as the query
parameter. I use Babel with Webpack. I tried the syntax in Chrome console and in Webpack source.
Is such a syntax supported by ES6? How does it work?
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.
Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.
Nope, JavaScript/EcmaScript don't support named parameters.
Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.
I recommend that you work around this with passing an object and using destructuring for objects:
function callApi({url, callback, query = {}, body = {}})
And then call it as:
callAPI({url: "/api/..", callback: (x => console.log(x)), body: {a:2}})
Which would give you syntax similar to the one you want.
Named arguments have been considered and rejected for JavaScript, unlike other languages like C# and Python which sport them. Here is a recent discussion about it from the language mailing list.
As shown on this site, the defaults are just for parameters that need a default value (like an options parameter), but not for 'skipping' parameters.
What you're trying to do is
// function definition function hi(a,b,c,d) // function call hi(a,b,d)
ES6 is still going to think that your 'd', is the defined c, regardless of your default value.
So no, ES6 does not have such syntax.
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