Skip to content
Advertisement

Javascript – Is it possible to put 2 values into 1 parameter of a function?

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?

Advertisement

Answer

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 })
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement