1

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?

2 Answers2

0

You can pass your arguments as an object.

function changeDir({x=0, y=0}){
     console.log(x, y)
}
         
changeDir({y:5})
norbekoff
  • 1,719
  • 1
  • 10
  • 21
  • This is already covered in the duplicate https://stackoverflow.com/a/11796776/542251 – Liam Apr 06 '22 at 15:39
0

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
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • This is already covered in the duplicate https://stackoverflow.com/a/11796776/542251 – Liam Apr 06 '22 at 15:39
  • I don't know why you're feeling aggressive about it. We're here to learn from each other @Liam – Nick Vu Apr 06 '22 at 15:50
  • What exactly is aggressive about pointing out that this answer is a duplicate? The OP agreed and closed their question. You should probably read [What to do with answer on duplicate question?](https://meta.stackoverflow.com/questions/352194/what-to-do-with-answer-on-duplicate-question) – Liam Apr 06 '22 at 15:51
  • Oops, perhaps my mistake, I'm sorry for my bad thought. Somebody devoted all our answers and the author's question @Liam – Nick Vu Apr 06 '22 at 15:53
  • Well yes, this answer is just a duplicate, so it's not helpful, so it should be downvoted, that's how voting works. – Liam Apr 06 '22 at 15:55
  • If you pointed out my answer is incorrect, I'd definitely agree, but you're thinking it's not helpful to the author (like you're doing that for the author even without her/his verification). If the author say it's not good or totally wrong, I'll delete it by myself for sure. I have been here for a while and I've seen many people asking very simple questions because they're new! we need to support them instead of being on check with them @Liam – Nick Vu Apr 06 '22 at 16:00