Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter names with ES6?

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?

like image 835
Jesvin Jose Avatar asked Sep 02 '15 12:09

Jesvin Jose


People also ask

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 Destructured parameter?

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.

Does JavaScript support named function?

Nope, JavaScript/EcmaScript don't support named parameters.

Why will you use default parameters es6?

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.


2 Answers

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.

like image 80
Benjamin Gruenbaum Avatar answered Sep 18 '22 12:09

Benjamin Gruenbaum


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.

like image 20
CherryNerd Avatar answered Sep 17 '22 12:09

CherryNerd