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": "[email protected]", "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})

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

So the query is not directly supported in JS! But this is the nice alternative solution... Thanks

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.