In this JavaScript lesson we are going to talk about JavaScript REST Operator, so It is used to handle function parameters, you can use three dot (…) for this. Rest operator signify that parameter is a placeholder for any number of arguments. and rest operator is used for handling function parameters. the best thing is this that the rest parameter is of Array type.
For example we have a function, in this function we have added a parameter, now when we call our function we can just add one parameter and it will print just one parameter.
1 2 3 4 5 6 |
function mynumbers(nums) { console.log(nums) } mynumbers(7,8,9) |
Even tough you can use arguments for print different parameters.
1 2 3 4 5 6 |
function mynumbers(nums) { console.log(arguments) } mynumbers(7,8,9) |
But in JavaScript ES6 we have another operator to do this, you can use REST Operator for performing of these kind functionalities.
1 2 3 4 5 6 |
function mynumbers(...nums) { console.log(nums) } mynumbers(7,8,9) |
JavaScript REST Operator Features
We already have talked that REST operator in JavaScript is represented by three dots (…) and it is used to gather the remaining arguments of a function or the remaining elements of an array. these are some features of REST operator in JavaScript:
- Gathering Function Arguments: The REST operator can be used to gather the remaining arguments of function into an array. this is useful when function takes a variable number of arguments.
1 2 3 4 5 6 7 8 9 10 |
function sum(...numbers) { let total = 0; for (let num of numbers) { total += num; } return total; } console.log(sum(1, 2, 3)); // Output: 6 console.log(sum(4, 5, 6, 7)); // Output: 22 |
- Destructuring an Array: REST operator can be used to gather the remaining elements of an array into new array.
1 2 3 4 5 6 |
const numbers = [1, 2, 3, 4, 5]; const [first, second, ...rest] = numbers; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(rest); // Output: [3, 4, 5] |
- Combining Arrays: REST operator can be used to combine two or more arrays into single array.
1 2 3 4 5 |
const numbers1 = [1, 2, 3]; const numbers2 = [4, 5, 6]; const allNumbers = [...numbers1, ...numbers2]; console.log(allNumbers); // Output: [1, 2, 3, 4, 5, 6] |
- Ignoring Function Arguments: REST operator can be used to ignore some of the arguments passed to function.
1 2 3 4 5 6 7 8 9 10 |
function printNames(first, second, ...rest) { console.log(`First name: ${first}`); console.log(`Second name: ${second}`); // Ignoring other names } printNames("John", "Doe", "Jane", "Smith", "Mike"); // Output: // First name: John // Second name: Doe |
In result we can say that REST operator in JavaScript provides lot of flexibility and can help simplify code in many situations.