Distinguishing the Spread and Rest Operator in JavaScript: An Interview Question

Posted by

JavaScript Interview Question – Difference between Spread and Rest Operator

JavaScript Interview Question – Difference between Spread and Rest Operator

In JavaScript, the spread and rest operators are two important features that can be used in different ways. It is important for a JavaScript developer to understand the difference between these two operators in order to use them effectively in their code.

Spread Operator

The spread operator, denoted by three dots (…), allows an iterable such as an array or string to be expanded into individual elements. It is commonly used to make copies of arrays, merge arrays, or spread the elements of an array as arguments to a function.

For example:


let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

Rest Operator

The rest operator, also denoted by three dots (…), is used to represent an indefinite number of arguments as an array. It is often used in function parameters to collect any remaining arguments into a single array.

For example:


function sum(...numbers) {
return numbers.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

Difference between Spread and Rest Operator

The key difference between the spread and rest operators is how they are used. The spread operator is used to expand an iterable into individual elements, while the rest operator is used to collect individual elements into an array.

Additionally, the spread operator is used in places where zero or more elements are expected (e.g., function arguments, array literals), while the rest operator is typically used in function parameters to represent any remaining arguments.

Conclusion

Understanding the difference between the spread and rest operators is important for JavaScript developers. By knowing when and how to use these operators, developers can write more efficient and readable code.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@prasantakumarroutray2105
10 months ago

You have excellent explanation..Keep it up.Nice