'Is there a way to pass a variable by its name in a function? [duplicate]

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?



Solution 1:[1]

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

Solution 2:[2]

You can pass your arguments as an object.

function changeDir({x=0, y=0}){
     console.log(x, y)
}
         
changeDir({y:5})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nick Vu
Solution 2