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?
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?
Share Improve this question asked Mar 11, 2021 at 16:50 HaezerHaezer 4765 silver badges19 bronze badges 2- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – ASDFGerte Commented Mar 11, 2021 at 16:53
- Does this answer your question? Syntax for destructuring arrays into function parameters in ES6 – ASDFGerte Commented Mar 11, 2021 at 16:59
4 Answers
Reset to default 9You 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
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);
This can be achieved using the ...
(spread) operator.
const user = ["John", "Doe"]
function fullName(firstName, lastName) {
return firstName + ' ' + lastName;
}
fullName(...user);
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