What is Spread Syntax and Rest Parameters? Are they related to each other?
I read about both but, I couldn't fully understand there use and purpose.
Any help would be much appreciated!
What is Spread Syntax and Rest Parameters? Are they related to each other?
I read about both but, I couldn't fully understand there use and purpose.
Any help would be much appreciated!
Spread syntax and Rest Parameters
I strongly recommend taking a look at the documentation, as it is very comprehensive and informative.
Spread syntax allows an iterable such as an array expression to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Example:
const array1 = [0, 1, 2, 3];
const array2 = [...array1, 4, 5, 6];
// array2 = [0, 1, 2, 3, 4, 5, 6,]
// Iterates over all properties of the specified object, adding it to the new object
// let objClone = { ...obj };
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
Example:
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3