The Spread Operator Part 1
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 18 of 65.
The spread operator (...) has many use cases for JSON. For instance, when doing the following operation:
const obj1 = {key1: "123"}
const obj2 = obj1
obj1.key1 = "456
console.log(obj2.key1)What would be the output?
console.log(obj2.key1)
// Output: "456"This might be surprising! Even though we only changed obj1, obj2 also changed.
This happens because when we assign objects directly (obj2 = obj1), we're creating a reference, not a copy. Both variables point to the same object in memory.
This is where the spread operator becomes useful. Let's see how to create a true copy:
const obj1 = {key1: "123"};
const obj2 = {...obj1};
obj1.key1 = "456";
console.log(obj2.key1);
// Output: "123"The spread operator creates a new object and copies all enumerable properties from the source object into the new one.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Cheat sheet
The spread operator (...) creates a copy of an object instead of a reference:
// Reference (both variables point to same object)
const obj1 = {key1: "123"}
const obj2 = obj1
obj1.key1 = "456"
console.log(obj2.key1) // Output: "456"// Copy using spread operator
const obj1 = {key1: "123"}
const obj2 = {...obj1}
obj1.key1 = "456"
console.log(obj2.key1) // Output: "123"The spread operator copies all enumerable properties from the source object into a new object.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys