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)
Example: Primitive types
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.
Example: Non Primitive types
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
Cloning:
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