JavaScript JunkiesJavaScript Junkies Unleash Your Coding Superpowers with JavaScript Junkies

Effortless Array Manipulation with Spread and Rest Operators in JavaScript

Spread Operator in JavaScript

The spread operator in JavaScript is represented by three dots “…” and is used to expand an iterable (e.g. an array or a string) into individual elements. It can be used in function calls to pass multiple arguments, or in array literals to concatenate multiple arrays.

Using Spread Operator in Function Calls

One common use case for the spread operator is in function calls, where it can be used to pass multiple arguments to a function. Here is an example:

function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 3];

const result = sum(...numbers);

console.log(result); // Output: 6

In this example, the sum() function takes three arguments and returns their sum. We create an array of three numbers and then use the spread operator to pass them as individual arguments to the sum() function. The output is 6, which is the sum of 1, 2, and 3.

Using Spread Operator in Array Literals

Another use case for the spread operator is in array literals, where it can be used to concatenate multiple arrays into a single array. Here is an example:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const concatenated = [...arr1, ...arr2];

console.log(concatenated); // Output: [1, 2, 3, 4, 5, 6]

In this example, we have two arrays, arr1 and arr2. We use the spread operator to expand each array into individual elements, and then concatenate them into a single array using the array literal syntax. The output is an array that contains all the elements from both arr1 and arr2.

Rest Operator

The rest operator is also denoted by three consecutive dots ..., but it is used in a different way than the spread operator. The rest operator is used to represent an indefinite number of arguments as an array in function declarations.

Using Rest Operator in Function

Here’s an example that shows how the rest operator can be used in a function:

function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

const result1 = sum(1, 2, 3);
const result2 = sum(4, 5, 6, 7);

console.log(result1); // Output: 6
console.log(result2); // Output: 22

In this example, the sum() function takes an indefinite number of arguments and returns their sum. We use the rest operator ...numbers to represent the arguments as an array. We then use the reduce() method to sum up all the numbers in the array. We can call the sum() function with any number of arguments, and it will always return their sum. In this case, we call the function with three numbers and four numbers, respectively, and get the expected results.

Press ESC to close