I know objects are passed by reference in javascript. so when I'm mutating an object in some other functions then it should be reflected in the initial object, which is not a case here, I might be missing something, it would be great if someone could help. here in the modify function I'm changing the object obj1 but still, it is showing the initial object.
Code
obj1 ={
b:{
c:'c'
},
d:{
g:{
k:'k'
}
}
}
let modify = (obj1) => {
obj1 = obj1.b ;
}
console.log(obj1);
modify(obj1);
console.log(obj1);
Output
//output of console1
[object Object] {
b: [object Object] {
c: "c"
},
d: [object Object] {
g: [object Object] { ... }
}
}
//output of console2
[object Object] {
b: [object Object] {
c: "c"
},
d: [object Object] {
g: [object Object] { ... }
}
}
3 Answers 3
What your code does is changing the reference on obj1 instead of changing something in the object that the reference if referring to.. Try replacing something in the object like the modified code below.
obj1 ={
b:{
c:'c'
},
d:{
g:{
k:'k'
}
}
}
let modify = (obj1) => {
obj1.d = obj1.b ;
}
console.log(obj1);
modify(obj1);
console.log(obj1);
Comments
You are not modifying your original object, you are just accessing his property:
let obj1 = {
a: 1,
b: 2
}
obj1 = obj1.b ;
console.log(obj1);
let obj1 = {
a: 1,
b: 2
}
console.log(obj1)
let obj2 = obj1;
obj2.c = 3;
console.log(obj1);
Comments
obj1 = obj1.b doesn't mutate anything because it merely re-assigns obj1 within the scope of modify(). However, any change you make to obj1, such as obj1.b.c='not c' will mutate the original object.
Here's an example that hopefully demonstrates this.
obj1 = {b:2}
obj2 = obj1
obj1 = 2
console.log(obj2);