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?
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.