Spread and rest
What is spread and rest ?
Spread is a syntax and rest is a parameter. Both have the same syntax i.e 3 dots followed by name of variable(...person) but different purposes.
Both are used in both arrays and objects.
Spread Syntax
The spread syntax allows you to expand elements of an iterable (like an array or string) or properties of an object. It is used to copy or combine values from one iterable or object to another.
Here are a few examples of spread syntax usage:
Copying an Array:
const originalArray = [1, 2, 3]; const newArray = [...originalArray]; console.log(newArray); // Output: [1, 2, 3]
In this example, the spread syntax ...originalArray expands the elements of originalArray and creates a new array newArray with the same elements.
Combining Arrays:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combinedArray = [...array1, ...array2]; console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Here, the spread syntax is used to combine the elements of array1 and array2 into a single array combinedArray.
Copying and Extending Objects:
const originalObject = { name: 'John', age: 30 }; const newObject = { ...originalObject }; console.log(newObject); // Output: { name: 'John', age: 30 }
The spread syntax can also be used to copy the properties of an object into a new object.
Rest parameters
The rest parameter syntax allows you to represent an indefinite number of arguments as an array. It is used in function declarations to gather multiple function arguments into an array.
Here's an example of using rest parameters in a function:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
In this example, the sum function uses rest parameters (...numbers) to gather all the provided arguments into an array called numbers. The function can then perform operations on the array of numbers.
When you wish to define a function that takes a variable amount of arguments, rest parameters are extremely helpful.
To recap, the rest parameter syntax is used to collect many function arguments into an array, whereas the spread syntax is used to extend or copy items from an iterable or attributes from an object/array. Although both features use the same spread syntax, they have different functions.