Rest parameters
The rest parameter syntax enables a function to have a variable number of arguments. When combined with destructuring assignment, rest parameters become an indispensable tool for dealing with arrays and objects.
Rest parameters are represented with the following syntax:
...rest
where rest
is a variable representing an iterable such as an array or object.
<<< Aside >>>
What is an iterable?
In simple terms, an iterable is a construct that represents a data structure that can be looped over, typically using a
for...of
loop.
<<< /Aside >>>
In function parameters
When a function's arguments exceeds the number of its parameters, the rest of the arguments can be packed into an array using rest parameters.
Here is how we could perform that operation:
const printFunctionParameters = (firstValue, secondValue, ...restOfValues) => {
console.log(`First value: ${firstValue}`);
console.log(`Second value: ${secondValue}`);
console.log(restOfValues);
}
printFunctionParameters('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Neptune', 'Uranus');
// 'First value: Mercury'
// 'Second value: Venus'
// ['Earth', 'Mars', 'Jupiter', 'Saturn', 'Neptune', 'Uranus']
Any argument that doesn't have a corresponding parameter would be packed into an array containing the rest of the function's arguments.
Using destructuring assignment
When using destructuring assignment, the iterable on the right side of the assignment operator, =
would be unpacked into the variables on the left. Any element, or property that wasn't extracted from the iterable would be packed into an array, or object depending on the type of destructuring used.
In array destructuring
Let's say we have an array of numbers
and we just need the first two elements for a task. Later on, we realize we need the remaining elements of the array.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
The best way to store these values would be to use the rest parameter syntax.
const [one, two, ...restOfNumbers] = numbers;
console.log(one);
// 1
console.log(two);
// 2
console.log(restOfNumbers);
// [3, 4, 5, 6, 7, 8, 9, 10]
In the code snippet above, the first and second elements of the array would be stored in the variables, one
and two
respectively. The remaining elements would be stored in an array called restOfNumbers
.
In strings
Imagine we have a string containing alphabets
and we want to access the first five alphabets and keep the remaining alphabets for later use.
Using the rest parameter syntax, we could store the remaining alphabets in an array.
const alphabets = 'abcdefghijklmnopqrstuvwxyz';
We can think of a string as an array of its characters.
const [a, b, c, d, e, ...restAlphabets] = alphabets;
In the snippet above, restAlphabets
would be an array containing alphabets from 'f'
to 'z'
.
In object destructuring
Rest parameter syntax with object destructuring works similarly with that of array destructuring.
However, in object destructuring, we extract the properties we need from the object, and then store the remaining properties in another object using the rest parameter syntax.
Assuming we have an object, jobDetails
and we want to extract a property called company
using object destructuring.
const jobDetails = {
company: 'Discourse',
level: 'junior',
role: 'Data scientist',
isVerified: true
};
After extracting the properties we need, we store the remaining properties in remainingDetails
using the rest parameter syntax.
const { company, ...remainingDetails } = jobDetails;
console.log(company);
// 'Discourse'
console.log(remainingDetails);
/*
{
level: 'junior',
role: 'Data scientist',
isVerified: true
}
*/
The variable containing the rest parameters must be the last parameter of a function or destructured iterable.
Spread syntax
The spread syntax notation is the same with that of rest parameters.
Spread syntax notation:
...variableName
The only difference is that variableName
represents an iterable such as arrays, objects or strings, which can be looped over.
Copying an array
To create a copy of an array, we simply unpack the elements of the original array into a new array by enclosing the unpacked elements in a set of square brackets.
const numbersCopy = [...numbers];
console.log(numbersCopy);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We can even add new elements to the unpacked array elements:
const listOfNumbers = [...numbers, 11, 12, 13, 14, 15];
console.log(listOfNumbers);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Concatenating arrays
To combine the elements of two or more arrays, we spread the elements of all the different arrays into a single array.
The resulting array would be a new array containing the elements of the constituent arrays.
const foodItems = ['eggs', 'bacon', 'cheese'];
const sports = ['volleyball', 'hockey'];
const mergedList = [...foodItems, ...sports];
Like we did before, we can decide to add new elements to the merged array if we want to.
const mergedList = ['kite', ...foodItems, false, ...sports];
Copying an object
To create a copy of an object, we simply spread out the properties of an existing object into a set of curly braces using the spread syntax.
const jobDetailsCopy = { ...jobDetails };
Merging objects
Imagine we had another object, extraJobDetails
which we want to combine with jobDetails
, to create a new object which would contain the properties of both existing objects.
const extraJobDetails = {
tools: ['MongoDB', 'Express', 'React', 'Node'],
languages: ['JavaScript', 'Python']
};
One of the best ways to perform this operation would be to use the spread syntax.
const updatedJobDetails = {
...jobDetails,
...extraJobDetails
};
Spreading strings
We can also spread out the characters of a string into an array using the spread syntax.
const alphabets = 'abcdefghijklmnopqrstuvwxyz';
const alphabetsArray = [...alphabets];
This would produce the same result as using the split
method of arrays with an argument of empty strings.
const alphabetsArrayUsingSplit = alphabets.split('');
๐งฌ BONUS: Rest + Spread ๐งฌ
The code snippet below is a simple JavaScript function that takes in a comma-separated list of numbers and outputs the highest number to the console.
const printHighestNumber = (...numberList) => {
const highestNumber = Math.max(...numberList);
console.log(highestNumber);
};
printHighestNumber(26, 51, 97, 64, 38);
// 97
printHighestNumber
accepts any number of inputs that is greater than or equal to 1.
In the set of parentheses enclosing the function's parameters, we first gather, or pack all the function's arguments into an array using rest parameters.
Then in the function body, we spread the array of arguments, numberList
into the Math.max()
method which returns the highest number from a list of numbers.
Thanks for reading.๐
Feel free to react and leave a comment.๐ฏ