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

1

2 Answers 2

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})

0
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'});

1
  • So the query is not directly supported in JS! But this is the nice alternative solution... Thanks
    – TalESid
    Oct 31, 2019 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.