⬅ Previous Topic
Iterating Over Arrays in JavaScriptNext Topic ⮕
Understanding the DOM Tree in JavaScript⬅ Previous Topic
Iterating Over Arrays in JavaScriptNext Topic ⮕
Understanding the DOM Tree in JavaScriptJavaScript's ...
(three dots) syntax is a powerful and flexible feature that behaves differently based on the context. It is used as:
The spread operator ...
allows you to expand elements of an array or object into individual elements.
const original = [1, 2, 3];
const copy = [...original];
console.log(copy);
Output:
[1, 2, 3]
This creates a shallow copy of the array. It is much safer than assigning copy = original
, which just points to the same reference.
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged);
Output:
[1, 2, 3, 4]
You can merge multiple arrays into one using the spread operator.
const numbers = [5, 6, 7];
console.log(Math.max(...numbers));
Output:
7
This is useful when passing an array as individual arguments to a function.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
Output:
{ a: 1, b: 3, c: 4 }
Note: Later properties overwrite earlier ones in case of conflict.
The rest operator also uses ...
, but instead of expanding, it gathers multiple elements into a single array or object. Its main use is in function parameters or object/array destructuring.
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
Output:
10
Question: Why can't we just define four parameters?
Answer: Because rest makes the function flexible—it can handle any number of arguments.
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
Output:
10 [20, 30, 40]
This is useful when you want to extract specific elements and collect the remaining ones.
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(a); // 1
console.log(others); // { b: 2, c: 3 }
Output:
1 { b: 2, c: 3 }
This helps separate one key from the rest of the object.
...spread
unpacks arrays or objects....rest
packs elements into arrays or objects.Question: What will the following code output?
const arr = [1, 2, 3];
const newArr = [0, ...arr, 4];
console.log(newArr);
Answer:
[0, 1, 2, 3, 4]
Both spread and rest are essential tools in modern JavaScript, enabling cleaner, more expressive code.
⬅ Previous Topic
Iterating Over Arrays in JavaScriptNext Topic ⮕
Understanding the DOM Tree in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.