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
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
Share Improve this question asked Oct 30, 2019 at 13:59 TalESidTalESid 2,5341 gold badge24 silver badges47 bronze badges 1- Possible duplicate of [Skip arguments in a JavaScript function ](stackoverflow./questions/32518615/…) – rassar Commented Oct 30, 2019 at 14:05
2 Answers
Reset to default 4You can achieve that by object destructions:
function post({ param1, param2 = "optional default value", param3 , param4}){
/// definitions
}
let param3 = 'abc';
post({param1: 'abc', param3})
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'});