Spread and rest operator in JavaScript can be used with syntax ‘…’. Although the syntax is the same it is called different as spread or rest based on its use.
Spread operator:
The spread operator is used to split up array elements or object properties.
Example of spread operator on array:
const students = ['John', 'Jane', 'Mike'];
const newStudents = [...students, 'Tom'];
console.log(newStudents);
Output:
[“John”, “Jane”, “Mike”, “Tom”]
Example of spread operator on object:
const student = {
id: 1,
firstnName:'John'
}
const updatedStudent = {
...student,
lastName: 'Doe'
}
console.log(updatedStudent);
Output:
{id: 1, firstnName: “John”, lastName: “Doe”}
Rest operator:
Rest operator is used to merging a list of function arguments in an array.
Example:
In the following examples, all arguments are passed using only one argument name and the rest operator.
const students = (...args) => {
return args.sort();
}
console.log(students('Sam', 'John', 'Mike', 'Jane', 'Tom'));
Output:
[“Jane”, “John”, “Mike”, “Sam”, “Tom”]
You learned how to use the spread and rest operator in JavaScript with different examples. If you have any questions, you can ask them through the comment section.