Spread Operator …


In JavaScript, the ... syntax is called the “spread operator.” It allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected. Here are some examples of how the spread operator can be used:

  1. Spread operator in function calls:
function myFunction(x, y, z) {
  console.log(x + y + z);
}

let args = [1, 2, 3];
myFunction(...args); // Output: 6

In this example, the spread operator is used to spread the args array into separate arguments for the myFunction function call.

  1. Spread operator in array literals:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // Output: [1, 2, 3, 4, 5, 6]

In this example, the spread operator is used to concatenate the arr1 array with additional elements to create the arr2 array.

  1. Spread operator in object literals:
let obj1 = { x: 1, y: 2 };
let obj2 = { ...obj1, z: 3 };
console.log(obj2); // Output: { x: 1, y: 2, z: 3 }

In this example, the spread operator is used to create a new object obj2 by merging the properties of obj1 with a new property z: 3.

Overall, the spread operator provides a concise and easy-to-read syntax for working with arrays, objects, and function arguments in JavaScript.