Lesson 20 - JavaScript Spread Operator
What is the Spread Operator?
The spread operator (...
) allows us to quickly copy all or part of an array or object into another array or object.
Example 1: Using Spread Operator with Arrays
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5, 6];
console.log(newNumbers);
// Output: [1, 2, 3, 4, 5, 6]
-
The
...numbers
spreads the values of numbers intonewNumbers
.Example 2: Combining Arrays
const arr1 = [10, 20, 30]; const arr2 = [40, 50, 60]; const combinedArr = [...arr1, ...arr2]; console.log(combinedArr); // Output: [10, 20, 30, 40, 50, 60]
- We use
...
to merge two arrays into a new one.
Example 3: Using Spread Operator with Objects
const person = { name: "Alice", age: 25 };
const updatedPerson = { ...person, city: "New York" };
console.log(updatedPerson);
// Output: { name: "Alice", age: 25, city: "New York" }
- The
...person
spreads all properties fromperson
intoupdatedPerson
, then we add a new property city.
Example 4: Copying an Object Without Mutation
const car = { brand: "Toyota", model: "Corolla" };
const carCopy = { ...car };
console.log(carCopy);
// Output: { brand: "Toyota", model: "Corolla" }
- This is useful when we want to copy an object without modifying the original.
Try Your Hand
Let’s practice using the spread operator. Follow the steps below:
Steps:
1. Create a File:
- Create a new file named lesson20-spread-operator.html
2. Write the Code:
- Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 20 - Spread Operator</title>
</head>
<body>
<script>
const fruits = ["apple", "banana", "orange"];
const moreFruits = [...fruits, "grape", "mango"];
console.log("Fruits:", fruits);
console.log("More Fruits:", moreFruits);
const user = { name: "John", age: 30 };
const updatedUser = { ...user, country: "USA" };
console.log("User:", user);
console.log("Updated User:", updatedUser);
</script>
</body>
</html>
- Save the file in your folder.
3. Preview the File: Open the file in your browser and check the developer console.
Key Takeaways
- The spread operator (
...
) allows you to copyarrays
andobjects
. - You can use it to merge arrays and objects.
- It prevents direct mutation of objects, making it useful in functional programming.