0

I have define an object in variable "c". I have also make a function in which I passed a object. When I do changes in that variable it is also changing original object but my concern is why below given statement is not working with that object. fiddle

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};
var m=c;
changeParam(a, b, c);

console.log(c)
console.log(m)
Cœur
  • 37,241
  • 25
  • 195
  • 267
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • 1
    "When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function." - http://snook.ca/archives/javascript/javascript_pass – BatScream Nov 18 '14 at 19:08
  • 1
    Which statement are you asking about specifically? And, what do you mean by "not working?" What do you expect to happen? – Jonathan Lonowski Nov 18 '14 at 19:09
  • if we are adding key3 in that object then it is there but when we are asign whole new object to "z" then it is not working – Jitender Nov 18 '14 at 19:10
  • What do you use `x` and `y` for? They seem to be totally useless. – Bergi Nov 18 '14 at 19:26
  • I think I have found an answer http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Jitender Nov 18 '14 at 19:31

1 Answers1

0

JavaScript passes object by reference. To pass it by value you need to clone it before.

In this question you'll find options of doing it. There are a lot ways of doing it, each with advantages and disadvantages. Depends on what you want from your object you can choose one.

Shortest way is to stringify object to JSON and parse again. (note that you can not save function in such object):

var newObject = JSON.parse(JSON.stringify(oldObject));

Works well with your jsfiddle

If you are using jquery in your project, you could use "jquery way" as well:

var newObject =  jQuery.extend(true, {}, oldObject);
Community
  • 1
  • 1
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79