What are spread and rest operators in JavaScript?
Understand how spread and rest operators simplify working with arrays, objects, and functions.
Advertisement
Question
What are spread and rest operators in JavaScript?
Answer
Both use ... but serve different purposes:
Spread (...) expands arrays or objects:
const arr = [1, 2, 3];
const clone = [...arr];
Rest (...) collects multiple arguments into one array:
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
Real-World Example
Spread and rest simplify React props handling, array merging, and function arguments.
Quick Practice
Write a function that takes any number of parameters and returns their sum using the rest operator.
Summary
Spread expands. Rest collects. Both use ..., but serve opposite purposes.
Can spread and rest be used together?
Yes, rest collects parameters while spread expands them — perfect for flexible function arguments.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement