2

In python we can omit a parameter with its default value in a function call. e.g.

def post(url, params={}, body={}):
    print()
    print(url)
    print(params)
    print(body)

post("http://localhost/users")

post("http://localhost/users", {"firstname": "John", "lastname": "Doe"})           # Skipped last argument (possible in JS as well)
post("http://localhost/users", params={"firstname": "John", "lastname": "Doe"})    # same as above

post("http://localhost", body={"email": "user@email.com", "password": "secret"})   # Skipped 2nd argument by passing last one with name (i.e. "body")

Can I achieve this in JS? Like omitting the 2nd argument and just pass the last one. (As in the last case). Other cases are possible in JS but I can't find a way to achieve the last one

TalESid
  • 2,304
  • 1
  • 20
  • 41
  • Possible duplicate of [Skip arguments in a JavaScript function ](https://stackoverflow.com/questions/32518615/skip-arguments-in-a-javascript-function) – rassar Oct 30 '19 at 14:05

2 Answers2

4

You can achieve that by object destructions:

function post({ param1, param2 = "optional default value", param3 , param4}){
 /// definitions
}

let param3 = 'abc';
post({param1: 'abc', param3})

Hossein Alipour
  • 575
  • 5
  • 9
3

You cant ommit a parameter and call it by its name. Omitting in js would mean to pass undefined so if your post was a 3 argument function you would do

post('http://whatever', undefined,'somebody')

So that the second param takes the default value

However what you can do is take an object as the parameter, destructure and assign default values:

function post({url,params={},body={}}){
}

Then to call the function you would do post({url:'http://whatever',body:'somebody'});

jstuartmilne
  • 4,398
  • 1
  • 20
  • 30
  • So the query is not directly supported in JS! But this is the nice alternative solution... Thanks – TalESid Oct 31 '19 at 06:35