What is the Difference between Spread and Rest Operator in JavaScript
Himanshu Gupta
Posted on February 28, 2024
Spread Operator (...) Details:
Expanding Iterables: The spread operator is primarily used to expand an iterable (like arrays, strings, etc.) into individual elements. It essentially spreads the values of an iterable into a new context.
Copying Arrays: When used with arrays, the spread operator creates a shallow copy of the array. This means it creates a new array and copies over the values from the original array.
Concatenating Arrays: It allows for easily concatenating or merging multiple arrays into a single array.
Passing Arguments: Spread is frequently used when calling functions that expect a variable number of arguments. It can pass each element of an array as an argument to the function.
Object Literals: It can also be used to merge properties of objects into a new object.
Iterating Over Strings: With strings, the spread operator can be used to split the string into individual characters.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
Rest Parameter (...args) Details:
Collecting Function Arguments: The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. This is particularly useful when you want to create functions that can accept a variable number of arguments.
Collecting Remaining Array Elements: In array destructuring, the rest parameter collects the remaining elements into a new array. This can be helpful when you want to extract certain elements from an array and gather the rest into a separate variable.
Combining with Destructuring: Rest parameters can be combined with array destructuring to collect remaining elements into a separate array. This allows for flexible handling of arrays, especially when the length of the array is not fixed.
Function Signatures: Rest parameters are commonly used in function signatures to indicate that a function can accept multiple arguments and gather them into an array within the function body.
function sum(...args) {
return args.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Outputs: 10
Posted on February 28, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 23, 2024