Course

Shallow Cloning

Loading...

In this lesson, you'll learn about cloning arrays and objects in JavaScript, which is essential for creating independent copies of data structures without maintaining references to the original.

Cloning Arrays

When you want to create a copy of an array without keeping a reference to the original, you can use several methods. Let's explore these methods and understand how they work.

  • Spread Operator
  • Array.slice()

Spread Operator

The spread operator is a modern addition to JavaScript that allows you to "spread" the values of arrays, objects, and strings. It's a concise way to clone arrays.

How to use

Imagine you have an array:

const numbers = [1, 2, 3, 4, 5];
const newNumbers = [...numbers];

The spread operator takes all the elements from the array and spreads them into a new array .

console.log(...numbers); // 1, 2, 3, 4, 5
console.log(newNumbers); // [1, 2, 3, 4, 5]

Checking Equality

Let's compare the original and copied arrays:

const copiedNumbers = numbers;

console.log(numbers === copiedNumbers); // true
console.log(numbers === newNumbers); // false
  • points to the same memory location as , so changes to one affect the other.
  • is a separate array, so changes to do not affect it.

Modifying the Original Array

numbers.push(6);

console.log(numbers); // [1, 2, 3, 4, 5, 6]
console.log(copiedNumbers); // [1, 2, 3, 4, 5, 6]
console.log(newNumbers); // [1, 2, 3, 4, 5]

The array remains unchanged, demonstrating that it is a "shallow clone".

Array.slice()

The method can also be used to clone an array:

const numbers = [1, 2, 3, 4, 5];
const numbersCopy = numbers.slice();

console.log(numbersCopy); // [1, 2, 3, 4, 5]

Cloning Objects

Just like arrays, objects can be cloned using similar methods.

  • Spread Operator
  • Object.assign()

Spread Operator

You can clone objects using the spread operator:

const person = {
    name: 'Jon',
    age: 20,
};

const otherPerson = { ...person };

// Modify the cloned object
otherPerson.age = 21;

console.log(person); // { name: 'Jon', age: 20 }
console.log(otherPerson); // { name: 'Jon', age: 21 }

Object.assign()

The method can also be used to clone objects:

const A1 = { a: "2" };
const A2 = Object.assign({}, A1);

console.log(A2); // { a: "2" }

Conclusion

We've learned two different ways to clone both objects and arrays: using the spread operator and using or .

These methods create shallow clones meaning they copy the top-level properties but not nested objects.

In the next lesson, we'll explore the difference between shallow and deep clones and how to create a deep clone. Understanding these concepts is crucial for managing data effectively in JavaScript.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Deep Cloning