- # Passing Arrays as Function Arguments
- # Example: Find the Largest Number
- # Explaining spread in non-dev terms
- # Passing Multiple Arrays as Function Arguments
- # What is a variadic function?
- How to pass arrays as function arguments in JavaScript?
- Passing arrays as function arguments
- Example
- Output
- Example
- Using an Array as Function Parameter in JavaScript
- How to use arrays as function parameters
- Passing arrays to functions with the spread operator
- Passing arrays to functions using apply()
- More Tips and Tricks for Javascript
- Passing Array to Function in JavaScript
- Function Receiving an Array via Function Call
- Passing Array to Function as Pass by Reference
- Passing Individual Array Element to Function as Pass by Value
# Passing Arrays as Function Arguments
The ability to turn an array into a list of arguments is super handy with the Math functions.
# Example: Find the Largest Number
Let’s say you want to find the largest number using the Math.max() function.
const largest = Math.max(5, 7, 3, 4); console.log(largest); // 7
But rarely, would you pass in individual values. More likely, you would want to find the maximum element in an array. So the question now is, how do you pass an array of values into a function that accepts individual arguments and NOT an array?
const numbers = [5, 7, 3]; // 🤮 Yuck! Math.max(numbers[0], numbers[1], numbers[2]); // ❌ And this won't work Math.max(numbers); // NaN
Lucky for us, we can use ES6’s Spread operator!
const numbers = [5, 7, 3]; // 😍 Much Better! Math.max(. numbers); // 7
What spread is doing here is taking the array element and expanding or unpacking it into a list of arguments for our variadic function.
const numbers = [5, 7, 3]; console.log(. numbers); // 5 7 3
# Explaining spread in non-dev terms
If you find this spread-ing thing still confusing. Maybe let me try to explain it with Russian nesting dolls
. So I like to think of the array as Russian nesting dolls. And what spread does is:
- It unpacks (spread) the nested dolls into individual dolls.
- And now you have all these individual dolls (arguments) to place nicely in your display case (function).
Not sure if this explanation helps? Leave a comment if it does, and I’ll start explaining programming concepts in fun ways like this 😆
# Passing Multiple Arrays as Function Arguments
Another superpower spread has is combining arrays.
const one = [1, 2, 3]; const two = [4, 5, 6]; const merged = [. one, . two]; // [ 1, 2, 3, 4, 5, 6 ]
So we can use this superpower to pass multiple arrays as function arguments 💪
const one = [1, 2, 3]; const two = [4, 5, 6]; Math.max(. one, . two); // 6
For those keeners, wondering if you can pass in 3 arrays. Well, you betcha! It’s like the energizer bunny, it keeps going and going and going . (This post is not sponsored by Energizer lol. But that can change, hit me up Energizer. Me want some sponsor money 😂)
const one = [1, 2, 3]; const two = [4, 5, 6]; const three = [2, 100, 2]; Math.max(. one, . two, . three); // 100
# What is a variadic function?
So you may notice I use the term variadic functions. The computer science folks will have probably heard this term. But for the rest of the cool bees like myself 😝, it may not be so familiar. A variadic function is a function that accepts an infinite or variable number of arguments. And the Math.max() function is one of those variadic function.
How to pass arrays as function arguments in JavaScript?
Passing arrays as function arguments
In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don’t need to use apply() function. Lets’ discuss it in a nutshell.
Example
In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used.
Output
If we observe the following example, apply() function and null weren’t used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value.
Example
Using an Array as Function Parameter in JavaScript
In Javascript, we often have data stored as arrays, and functions we want to call. Sometimes, the data in our arrays is exactly the data we want to pass to a function. Fortunately, there are ways in Javascript to use arrays as the input values for functions. Let’s look at how to use arrays as function parameters.
How to use arrays as function parameters
When we have a function we want to pass an array to, the most basic way to do it would be like this:
let numbers = [ 1, 2, 3 ] let myFunction = (x, y, z) => return x + y + z; > // Returns 6 let getCalculation = myFunction(numbers[0], numbers[1], numbers[2]);
Of course, this can be quite annoying, especially when working with functions which have very long lists of properties. As such, Javascript provides us with two ways to use arrays as function parameters in Javascript — apply() and the spread operator.
Passing arrays to functions with the spread operator
The modern, and easiest way to pass an array to a function is to use the spread operator. The spread operator ( . ) is simply added before the array. Using our previous example, it looks like this:
let numbers = [ 1, 2, 3 ] let myFunction = (x, y, z) => return x + y + z; > // Returns 6 let getCalculation = myFunction(. numbers);
We can also directly add the array into the function, without needing a variable. For example:
let myFunction = (x, y, z) => return x + y + z; > // Returns 6 let getCalculation = myFunction(. [ 1, 2, 3 ]);
Passing arrays to functions using apply()
The other way to do this, is to use apply() . If you’re unfamiliar with the main use case of apply() , check out my full guide on Javascript’s this object here.
Ultimately, apply() lets us take a function, and pass an array into it. The first attribute of apply() actually refers to the this object we want to use on the function. The second argument is an array of all the parameters for that function. That means you can define the structure of this as well as pass an array into the function itself.
This obviously has some specific benefits when compared to the spread ( . ) operator, so it may be more suitable depending on what you want to achieve. Using our previous example, we can pass an array into our function like so:
let myFunction = (x, y, z) => return x + y + z; > // Returns 6 let getCalculation = myFunction.apply(>, [ 1, 2, 3 ]);
Here, I am leaving the this object empty, so if we did use this in myFunction , it’d be an empty object — that’s what the first argument of apply() does. The second is our array [1, 2, 3] , referring to x , y , and z respectively.
More Tips and Tricks for Javascript
Passing Array to Function in JavaScript
Similar to C/C++/Java, we can pass the entire array as a parameter to a function in JavaScript. This method of array passing is called call by reference in JavaScript.
To pass an array argument to a function, simply pass the name of an array (a reference to an array) without brackets.
For example, if we have declared an array marks as:
let hourlyTemp = new Array(30);
then function call statement:
passes array hourlyTemp to the function modifyArray(). JavaScript automatically passes arrays to functions using call-by-reference (or passed by reference).
Function Receiving an Array via Function Call
For a function to receive an array via a function call, you must specify a parameter in the function’s parameter list that will refer to the array in the function body.
Unlike other programming languages, JavaScript does not hand over any specific syntax for this purpose. JavaScript simply needs that the name of an array to be specified in the function parameter list.
For example, we can write the function definition for the function modifyArray as:
The above function definition indicates that modifyArray() receives an array of integers in parameter x (the argument supplied in the calling function must be an array).
When the called function uses the array name x, it points to the original array in the caller (array hourlyTemp).
Therefore, when the called function updates any array elements in its function body, it is updating the actual elements of the array in their original memory locations.
Passing Array to Function as Pass by Reference
1. Let’s create a JavaScript program in which we will pass an initialized array to a function. Then, we will multiply each array element by 5 and display it.
Output: Original array elements are: 20 10 25 15 35 40 Modified array elements: 100 50 125 75 175 200
In this example program, we have passed an array nums into modifyArray() as pass by reference. That is, the parameter nums is passed into modifyArray() function with reference to x. Inside the function the array elements are multiplied by 5 and displayed.
Output: Original array elements are: 10 20 30 40 50 Modified array elements are: 20 40 60 80 100
Passing Individual Array Element to Function as Pass by Value
Let’s create a JavaScript program in which we will pass the entire array as a pass by reference to the function in JavaScript. Then we will pass the individual array element to the function as a pass by value in JavaScript.
Program code 3:
Output: Original array: 10 20 30 40 50 Modified array: 40 80 120 160 200 nums[3] before modifyElement: 160 nums[3] after modifyElement: 480
Although the entire array is passed by reference, whereas individual numeric and boolean array elements are passed by value.
To pass an element of an array to a function, use the sub-scripted name of the element as an argument value in the function call.
In this tutorial, you learned an interesting topic “passing array to function in JavaScript” with many example programs. Hope that you will have understood how to pass an individual element of an array in JavaScript.
Thanks for reading.
Next ⇒ Arrays methods in JavaScript ⇐ Prev Next ⇒