I am trying to pass a variable into a function by its name in javascript, as you can in python:
def myFunction(x=0, y=0):
print(x, y)
myFunction(y=5)
>>> 0, 5
So far, I have been unable to find a way to do this:
function changeDir(x=0, y=0){
console.log(x, y)
}
changeDir(y=5)
>>> 5, 0
This changes x, not y. Is there a way to change y without having to pass undefined as the first value?
You should pass an object param instead of individual params
function changeDir({ x = 0, y = 0 } = {}){ // x = 0 and y = 0 are default values
console.log(x, y)
}
changeDir({ y: 5 }) //0,5
changeDir() //0,0
changeDir({x: 5}) //5,0
changeDir({y:5, x:10}) //10,5
You can pass your arguments as an object.
function changeDir({x=0, y=0}){
console.log(x, y)
}
changeDir({y:5})