Advance JavaScript - Spread Operator Tutorial

The spread operator is a feature in JavaScript that allows an expression to be expanded in places where multiple arguments are expected. The spread operator is represented by three dots (...).

For example, consider the following code:

let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = [...arr1, ...arr2]; console.log(arr3); // Output: [1, 2, 3, 4, 5, 6]


In this code, the spread operator is used to combine two arrays into a single array. The spread operator takes the elements of the first array (arr1) and expands them into separate elements, followed by the elements of the second array (arr2), which are also expanded into separate elements. The result is a new array (arr3) that contains all of the elements of both arrays.

The spread operator can also be used to spread the elements of an array into a function call, as in the following example:

function sum(a, b, c) {

  return a + b + c;

}


let arr = [1, 2, 3];

console.log(sum(...arr));

// Output: 6

In this code, the spread operator is used to spread the elements of the array into the function call, allowing the function to receive each element as a separate argument.

The spread operator is a useful feature in JavaScript that allows for more concise and flexible code. It can be used in a variety of contexts, such as arrays, function calls, and object literals, to make it easier to work with multiple elements at once.