Reputation: 1797
I have an object "a" and I assign it to another variable named "b". Now I delete some property values from "b" using delete keyword. It deletes that property from both objects "a" and "b". Why is that?
P.S: I am beginner in javascript. go easy on me.
Code: -
let a = {
a:1,
b:2,
c:3
}
let b = a;
console.log(a); // output { a: 1, b: 2, c: 3 }
delete b.a;
console.log(a) // Expected output { a: 1, b: 2, c: 3 } -- Actual output { b: 2, c: 3 }
Upvotes: 2
Views: 227
Reputation: 4073
Your question is more related to the fact that some types are assigned by value and others by reference.
In a quick summary
Primitive types are assigned by value (Boolean, Null, Undefined, Number, String, Symbol (new in ES 6))
Non Primitive types are assigned by reference (Object, Array , Functions)
let a = 1;
let b = a;
console.log(a); // 1
console.log(b); // 1
b = 2;
console.log(a); // 1
console.log(b); // 2
As you can see changing b
will not affect a
because number is assigned by value.
let a = { name: 'Amr' };
let b = a;
console.log(a); // { name: 'Amr' };
console.log(b); // { name: 'Amr' };
b.name = "John";
console.log(a); // { name: 'John' };
console.log(b); // { name: 'John' };
As you can see changing b
affected the value of a
because it is assigned by reference, this is similar to your example, the issue is not related to delete
but it is related to the fact that objects are assigned by reference so deleting key from b
will affect a
in some situations you will need to clone your non primitive type object and not mutating the current one, you can do that using the following way:
ES5 var clone = Object.assign({}, obj);
OR
var clone = JSON.parse(JSON.stringify(obj));
ES6 var clone = { ...obj };
now updating clone
will not affect obj
Finally You can read more about this topic in this link it can give you a better understanding on how this works with memory assignment illustrations
Upvotes: 2
Reputation: 86
Java script array are copied through copy by reference. So if you edit the copied array, the original array will be changed. You can use
let b = a. slice()
Or
Spread operator in ES6. let b = [... a]
Upvotes: 0
Reputation: 8239
When you do :
let b = a;
You just pass reference of the object a to b. So a and b points to the same reference. Therefore changes made in any one of them will reflect in other.
Basically you have something in the memory as:
a:ref12345−−−+
|
|
| +−−−−−−−−−−−−−+
+−−−>| (object) |
| +−−−−−−−−−−−−−+
| | prop1: "a" |
| | prop2: "b" |
b :ref12345−−+ | prop3: "c" |
| |
+−−−−−−−−−−−−−+
Upvotes: 0