0

Suppose I have a function as this:

function test(a, b, c, d) {
...
}

Is there a way that I can pass my inputs into the function as follows:

test(a:1,c;2)
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Henry Hung
  • 35
  • 1
  • 8
  • 2
    JavaScript doesn’t support passing function arguments by name. Are you looking for `test(1, undefined, 2, undefined)`? – Ry- Jul 14 '17 at 04:04
  • you can do something like `function test(o={a:1,b:2,c:3, d:4 })` then call `test({a: 1, c:2 })` – T4rk1n Jul 14 '17 at 04:07
  • @Ryan Thanks for your comment. I know that will work but I just want to know is there exist a way allowing me to pass certain inputs into function. – Henry Hung Jul 14 '17 at 04:07
  • Thanks to both T4rk1n and huydq5000 answers! That works! – Henry Hung Jul 14 '17 at 04:18

2 Answers2

0

Named values doesn't support in a function, you have 2 options:

  • Pass undefined value to unused variable like test(1, undefined, 2, undefined)
  • Modified the parameters as an object like test(obj) and use obj.a, obj.b,... to pass the values
huydq5000
  • 274
  • 1
  • 8
0

You can not as you exactly suggested, but you could have your function take an object with your arguments as fields.

Ex:

function test(myArguments) {
    if (myArguments.a) {
      // do something with myArguments.a
    }
    ...
}

Call as:

test({a: 1, b: 2});
Rob C
  • 2,103
  • 1
  • 11
  • 13