5

Is there a way to unpack an array as arguments for a function?

For example in python if I have:

user = ["John", "Doe"]

def full_name(first_name, last_name):
    return first_name + last_name

Then full_name(*user) unpack my user array and pass each of its items as argument of full_name.

Is that possible to achieve such a behavior in JavaScript/TypeScript?

Haezer
  • 457
  • 5
  • 15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – ASDFGerte Mar 11 '21 at 16:53
  • Does this answer your question? [Syntax for destructuring arrays into function parameters in ES6](https://stackoverflow.com/questions/36961080/syntax-for-destructuring-arrays-into-function-parameters-in-es6) – ASDFGerte Mar 11 '21 at 16:59

4 Answers4

8

You want the ...spread operator.

const user = ["John", "Doe"] as const

function fullName(firstName: string, lastName: string): string {
    return firstName + lastName
}

fullName(...user)

Note the as const.

In order for this to have type safety in Typescript, the array needs to be a two item tuple of type [string, string] and not just an array of unknown length like string[]. This is because in order to guarantee type safety there must be at least 2 strings in that array in order to satisfy both arguments. as const forces typescript to treat that array as a tuple with known strings and length instead.

Playground

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
2

You could either apply array desctructuring on the parameter of the full_name function:

const user = ["John", "Doe"];

const full_name = ([first_name, last_name]) =>
    first_name + last_name;

full_name(user);

or use the spread operator (...) when you call full_name with the array parameter.

const user = ["John", "Doe"];

const full_name = (first_name, last_name) =>
    first_name + last_name;

full_name(...user);
kruschid
  • 759
  • 4
  • 10
2

Try Destructuring assignment. Like this:

const full_name = (arr) => {
    const [firstname, lastname] = arr;
    return `${firstname} ${lastname}`;
};

var user = ["John", "Doe"];
console.log(full_name(user)); // result: John Doe
Petr Fořt Fru-Fru
  • 858
  • 2
  • 8
  • 23
1

This can be achieved using the ... (spread) operator.

const user = ["John", "Doe"]

function fullName(firstName, lastName) {
    return firstName + ' ' + lastName;
}

fullName(...user);