1

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] { ... }
 }
}
asked Jan 10, 2021 at 18:41

3 Answers 3

1

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);
answered Jan 10, 2021 at 18:58
Sign up to request clarification or add additional context in comments.

Comments

0

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);
If you create an object from other object, you are passing the reference to his object, to see how the original object is mutated check out this example:

let obj1 = {
a: 1,
b: 2
}
console.log(obj1)
let obj2 = obj1;
obj2.c = 3;
console.log(obj1);

answered Jan 10, 2021 at 18:56

Comments

0

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);

answered Jan 10, 2021 at 18:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.