Explain Codes LogoExplain Codes Logo

Passing an array as a function parameter in JavaScript

javascript
spread-operator
function-parameters
array-manipulation
Anton ShumikhinbyAnton Shumikhin·Jan 28, 2025
TLDR

You can pass an array to a function by treating it as a regular variable. When creating your function, define a parameter, which you can then utilize to manipulate the array inside the function.

Example:

// Function to calculate sum of array elements function sumElements(numbers) { return numbers.reduce((sum, num) => sum + num, 0); } const result = sumElements([1, 2, 3]); // Should return 6, simple math!

Here, for the sumElements function, we're tallying up the sums of all elements within the passed array using reduce.

To individually pass elements from an array as separate arguments, ES6 has introduced us to the wonderful inventor, the spread operator (...):

// An addition function for three numbers function add(a, b, c) { return a + b + c; } const nums = [1, 2, 3]; const result = add(...nums); // Like spreading butter on bread, each number gets its own spot

Old but gold, Function.prototype.apply(), comes to save the day when the spread operator fails to be compatible:

const result = add.apply(null, nums); // 'null' sets the 'this' context to global, apply's got your back!

Both apply() and the spread operator smoothly maintain their work charm!

Express manners with arrays in function

Diving deep with spread operator

The spread operator (...) in ES6 paves an easier path for passing array elements like individual arguments in a function:

// Greet someone function greet(first, last) { console.log(`Hello, ${first} ${last}!`); } const names = ['Jane', 'Doe']; greet(...names); // "Hello, Jane Doe!"

The golden alternative: apply method

apply() is the knight in shining armor for situations with varying lengths of arrays:

// Function to greet function greet() { console.log(`Hello, ${this.first} ${this.last}!`); } const person = { first: 'Jane', last: 'Doe' }; const names = ['John', 'Smith']; greet.apply(person); // Context from 'person' object greet.apply(null, names); // Global context, names passed as arguments

Swagger in iteration within functions

To flaunt your function while manipulating arrays, use loops or forEach method:

// Function to process array function process(array) { array.forEach(item => { // twist and turn item in every possible way }); }

Dealing with arrays like a Pro

You've got mail! Ahem, large arrays

Handling large arrays? Brace for the performance hit. Spreading large arrays might be as hard as spreading cold butter:

// Might take a while for a marathon of elements function process(...largeArray) { // ... }

When dealing with large arrays, it could be more efficient to pass it as a single array argument and process it within the function.

The context circus

Let's not forget about this context. If your function needs it, then the choice between apply() and spread is determined by your function design.

The real-world rollercoaster

Think of API calls scenarios where an array of data is often part of endpoint URLs:

function fetchData(resource, ...params) { let query = params.join('&'); return fetch(`${resource}?${query}`); // API calls done right! }