Today I have faced a new issue while coding in NodeJS I was fetching a record from DB which is an object which will contain an object array as well and I have assigned object array to a new variable lets call arr and I pushed a string into arr. And for some strange reasons, my original record also affected not sure why it has happened. I know about changing/reassigning an object will affect the original object but in this case am not sure why it has happened.
let original = {
a: 1,
branchIds: [ {
_id: "abc",
name: "abc"
}]
};
let arr = original.branchIds;
arr.push("sa");
console.log(original);
JsFiddle Link http://jsfiddle.net/jdqmLzbv/4/
arrto original.branchIds, so by calling.pushonarrit's pushing another item into the array of variableoriginal. What is unclear about this?arr=original.branchIdsyou are giving it a reference to the array held byoriginalso any changes made affect the original, Zohaib's answer explains it along with a solution.