0
var x = {'a': 't1', 'b': 't2', 'c': 't3'};
var y = x;
delete (y['c']);
console.log(x);

Expected output:

Object {a: "t1", b: "t2", c: "t3"}

Output:

Object {a: "t1", b: "t2"}

Is there any reason why deleting a property of object y changes object x?

chris97ong
  • 6,870
  • 7
  • 32
  • 52
  • 5
    Objects are passed by `reference` not by `value`. Both the variables are pointing same memory location hence if any of them changed will eventually change the object.. – Rayon Mar 28 '16 at 11:45
  • 3
    Because it's exactly the same object instance. – Álvaro González Mar 28 '16 at 11:45
  • @RayonDabre Then if I want to have an object y without key c and without affecting object x, how do I do it? – chris97ong Mar 28 '16 at 11:46
  • 2
    You have many options to achieve so.. Just search for `Deep copy of objects in JavaScript` – Rayon Mar 28 '16 at 11:47
  • checkout me. My answer [link](http://stackoverflow.com/questions/36261637/strange-behaviour-with-delete/36261790#36261790) – Murad Hasan Mar 28 '16 at 11:56
  • The marked duplicate "What is the most efficient way to clone an object?" is not a duplicate of this question, and the accepted answer isn't an answer to either that or this question. – RobG Mar 28 '16 at 11:56

4 Answers4

2

Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object. so in your case you are passing it by reference.

Rahul Pandey
  • 116
  • 6
1

Objects are passed by reference. The assignment operator changes the reference, not the value.

This is a common thing in most programming languages and you need to make a deep copy of the object if you don't want to modify x. You can see this thread.

Community
  • 1
  • 1
Mariy
  • 5,746
  • 4
  • 40
  • 57
1

When you assign a object to another variable its only the reference set. So manipulating either the main object or the assigned variable will still manipulate the same memory location. So you have to do a deep copy of the object into the variable which will create a new memory for the variable and then manipulate it. Here you can try this.

var y= Object.assign({}, x);
delete (y['c']);
console.log(x);
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
1

You have to copy the value, by default it takes the reference.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Scripts:

var x = {'a': 't1', 'b': 't2', 'c': 't3'};
var copy = Object.assign({}, x);
delete (copy.c);
console.log(x);
console.log(copy);

Output:

Object { a: "t1", b: "t2", c: "t3" }
Object { a: "t1", b: "t2" }

fiddle link

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42