
Rest and spread properties are features in Javascript that allow you to work with arrays and objects in more flexible and efficient ways.
Rest properties are used to collect the remaining properties or elements of an object or array that are not already assigned to a variable. This is done by using the spread operator (...
) followed by the name of the variable that will hold the remaining properties or elements. Rest properties are commonly used in function parameters to collect any remaining arguments passed to the function.
Here is an example of using rest properties in a function parameter:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
In this example, the sum
function takes any number of arguments and collects them into an array using rest properties. The reduce
method is then used to sum up all the numbers in the array and return the result.
Spread properties, on the other hand, are used to spread the properties or elements of an object or array into a new object or array. This is also done using the spread operator (...
). Spread properties are commonly used to combine or clone objects or arrays.
Here is an example of using spread properties to combine two objects:
const person = { name: 'John', age: 30 };
const job = { title: 'Developer', salary: 50000 };
const employee = { ...person, ...job };
console.log(employee); // Output: { name: 'John', age: 30, title: 'Developer', salary: 50000 }
In this example, the spread operator is used to combine the person
and job
objects into a new employee
object. The resulting object contains all the properties from both objects.
In summary, rest and spread properties are powerful features in Javascript that allow you to work with arrays and objects in more flexible and efficient ways. Rest properties are used to collect the remaining properties or elements of an object or array, while spread properties are used to spread the properties or elements of an object or array into a new object or array.