Home > database >  Javascript - Is it possible to put 2 values into 1 parameter of a function?
Javascript - Is it possible to put 2 values into 1 parameter of a function?

Time:05-05

Example:

const exampleFunq = function (exampleParameter, exampleParameterTwo) {

} 

Now when i invoke it, let's say i want to put 2 values into 2nd parameter;

exampleFunq(1, 2 3)

i know this code is wrong but is it a possible concept?

CodePudding user response:

JavaScript doesn't have tuples as language concept, but you can always pass an array or an object:

function example (arg1, arg2) {
  console.log(arg1, arg2[0], arg2[1])
}

example(123, [456, 789])
function example (arg1, arg2) {
  console.log(arg1, arg2.first, arg2.second)
}

example(123, { first: 456, second: 789 })

Using destructuring, you can make this seamless, if so desired:

function example (arg1, [arg2A, arg2B]) {
  console.log(arg1, arg2A, arg2B)
}

example(123, [456, 789])
function example (arg1, { first, second }) {
  console.log(arg1, first, second)
}

example(123, { first: 456, second: 789 })

CodePudding user response:

You could treat your 2nd (and 3rd, nth...) param as variable list of arguments.

const exampleFunq = (exampleParameter, ...additionalExampleParameters) => {
  console.log([exampleParameter, ...additionalExampleParameters]);
}

exampleFunq(1, 2)
exampleFunq(1, 2, 3)
.as-console-wrapper { top: 0; max-height: 100% !important; }

  • Related