The rest and spread operators in JavaScript | Lecture 7
The rest
and spread operators in JavaScript are represented by the ... syntax. They allow developers to work with arrays and objects in a more
flexible and concise way. Here’s a detailed explanation with examples:
Rest Operator (...)
The rest
operator collects multiple elements and condenses them into a single array
or object. It is primarily used in function arguments or destructuring
assignments.
Examples:
- Function Parameters:
2. function sum(...numbers) {
3. return
numbers.reduce((total, num) => total + num, 0);
4. }
5.
6. console.log(sum(1, 2, 3, 4)); // Output: 10
- Here, ...numbers collects all arguments
passed to the function into an array.
- Array Destructuring:
8. const [first, second, ...rest] = [1, 2, 3, 4, 5];
9. console.log(first); // Output: 1
10.console.log(second); // Output: 2
11.console.log(rest); // Output: [3, 4, 5]
- ...rest captures the remaining
elements after the first two.
- Object Destructuring:
13.const person = { name: "John", age: 25,
country: "USA", job: "Developer" };
14.const { name, ...details } = person;
15.
16.console.log(name); // Output: John
17.console.log(details); // Output: { age: 25,
country: 'USA', job: 'Developer' }
- ...details collects the remaining
properties of the object.
Spread Operator (...)
The spread
operator takes an array or object and expands its elements or properties.
Examples:
- Array Expansion:
2. const arr1 = [1, 2, 3];
3. const arr2 = [4, 5, 6];
4. const combined = [...arr1, ...arr2];
5.
6. console.log(combined); // Output: [1, 2, 3, 4, 5,
6]
- ...arr1 and ...arr2 expand the contents of the
arrays into the new array.
- Copying Arrays:
8. const original = [1, 2, 3];
9. const copy = [...original];
10.
11.console.log(copy); // Output: [1, 2, 3]
- The spread operator creates
a shallow copy of the array.
- Object Expansion:
13.const person = { name: "John", age: 25 };
14.const updatedPerson = { ...person, job:
"Developer" };
15.
16.console.log(updatedPerson);
17.// Output: { name: 'John', age: 25, job:
'Developer' }
- ...person expands the original
object's properties into the new object.
- Function Arguments:
19.const numbers = [1, 2, 3, 4];
20.console.log(Math.max(...numbers)); // Output: 4
- ...numbers spreads the array elements
as individual arguments for the function.
Key Differences:
|
Feature |
Rest Operator |
Spread Operator |
|
Purpose |
Collects
elements into an array or object. |
Expands
elements from an array or object. |
|
Usage |
In
function arguments or destructuring. |
When
combining arrays/objects or passing arguments. |
By
mastering the rest and spread operators, you can write cleaner,
more concise, and more flexible JavaScript code!
Comments
Post a Comment