Hello Friends 👋,

Welcome to Infinitbility.

When we assign one object data in another new variable still they both are connected to each other using the javascript reference concept or if change anything on the object variable you will same changes in another object.

For example, when we copy firstObject to secondObject and change secondObject it’s will change firstObject.

let firstObject = { a: 1, b: 2};

// copy objects with references
let secondObject = firstObject;
console.log("firstObject", firstObject);
console.log("secondObject", secondObject);

// assigning new element in the second object
secondObject.c = 3;

// affecting both objects
console.log("firstObject", firstObject);
console.log("secondObject", secondObject);
Javascript Object Referance
Javascript Object copy with Referance

Now, we know problem, let move to solution.

javascript provide multipe ways to create javascript object with data and Object.create() is one of them it will help you to copy object without any referance.

For test let use Object.create() method on our example.

let firstObject = { a: 1, b: 2};

// copy objects with references
let secondObject = Object.create(firstObject);
console.log("firstObject", firstObject);
console.log("secondObject", secondObject);

// assigning new element in the second object
secondObject.c = 3;

// affecting both objects
console.log("firstObject", firstObject);
console.log("secondObject", secondObject);
Javascript Object without Referance
Javascript Object copy without Referance

Conlustion, When we want copy any object without referance then we have to use object create method, it will copy data in new object.