JavaScript Object Copying: Shallow Copy vs Direct Assignment

1) Shallow Copy with an Empty Target Object :

Create a new object as the target and copy properties from the source. - Changes to the source object won't affect the copied object.

Example:

const first = {"name": "Ali"};

const sec = Object.assign({}, first);

first.name = "Ahmad";

console.log("first:", first); // Output: { "name": "Ahmad" }

console.log("Second:", sec); // Output: { "name": "Ali" }

2) Direct Assignment:

Copying an object without creating a new object.Changes to the source object affect the copied object because both reference the same data.

Example:

const first = {"name": "Ali"};

const sec = Object.assign(first);

first.name = "Ahmad";

console.log("first:", first); // Output: { "name": "Ahmad" }

console.log("Second:", sec); // Output: { "name": "Ahmad" }

要查看或添加评论,请登录

Talat Hussain的更多文章

社区洞察

其他会员也浏览了