I have a global Javascript object for which I set some values and push to an array. Once I push it to my array and update its values, it changes the already pushed values in the array. For example:
let obj1 = {"name":"", "age":""} //Assume this is declared outside the scope of the below block
{
obj1.name = "john";
obj1.age = 21;
arr1.push(obj1);
console.log(arr1) // [{name:"john", age:21}]
obj1.name = "mary"; //Object in array has already changed here
console.log(arr1) // [{name:"mary", age:21}]
obj1.age = 24;
arr1.push(obj1)
}
I want to understand why this happens and how I can avoid it from happening. I want to be able to push 2 different objects with different values to the array. Is the only way to do this by creating another object?