In JavaScript, you can pass an array to a function that expects a list of values using the spread operator (...). The spread operator allows you to expand the elements of an array into individual arguments when calling a function.
By using the spread operator, you can pass an array of values to a function as if they were individual arguments. This makes the code cleaner and more readable, especially when dealing with functions that expect multiple parameters.
See the examples given below:
const trees = ["Oak", "Maple", "Birch", "Pine"]; function identifyTrees(...treeNames) { for (const tree of treeNames) { console.log(`Identifying ${tree} tree...`); } } identifyTrees(...trees); // Output: Identifying each tree name
const colleges = ["MIT", "Stanford", "Harvard", "Caltech"]; function rankColleges(...collegeNames) { for (let i = 0; i < collegeNames.length; i++) { console.log(`${i + 1}. ${collegeNames[i]}`); } } rankColleges(...colleges); // Output: Ranking colleges in order
In the examples above, the identifyTrees function and the rankColleges function both use the spread operator in their parameter lists (...treeNames and ...collegeNames, respectively). This allows these functions to accept any number of arguments, effectively treating the elements of the arrays passed in as individual values.