Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow