ir3ne / javascript-questions-and-answers

🤓 A collection of JS questions about core concepts.
MIT License
6 stars 1 forks source link

What is a shallow copy? #14

Closed ir3ne closed 5 hours ago

ir3ne commented 2 weeks ago

See if add shallow copy of ..an object, etc

TBalo commented 1 week ago

What is a Shallow Copy?

A shallow copy is a duplicate of an object where the top-level properties are copied, but the nested objects or arrays are shared between the original and the copy. This means that if you modify a nested object in the copy, the change will also affect the original object, since both reference the same nested object.

Shallow Copy in JavaScript

In JavaScript, you can create a shallow copy of an object using several methods. Here are a few common techniques:

1. Using Object.assign()


const original = {
    name: "Alice",
    age: 25,
    address: {
        city: "Wonderland",
        zip: "12345"
    }
};

const shallowCopy = Object.assign({}, original);

shallowCopy.address.city = "New City";

console.log(original.address.city); 
ir3ne commented 1 week ago

hey @TBalo thanks for this contribution? would you like to open a PR for this?

TBalo commented 1 week ago

hey @TBalo thanks for this contribution? would you like to open a PR for this?

You're welcome @ir3ne.

Yeah sure..

You could assign it.