3

as you know, in javascript objects and arrays are send by reference and if we got something like this:

const obj=[{room:5},{room:35},{room:25},{room:15}];

static test(obj)
  {
    for (let i=0;i<obj.length;i++)
    {
      obj[i].room++;
    }
    return obj;
  }
return {ok:true,D:obj,R:this.test(obj)};

then the first object values would change after calling test, the question is how to prevent passing the object by reference and its modifications !??!

Godfather
  • 342
  • 4
  • 18
  • `Object.freeze(obj[0])` ... Objects are always passed by reference, if you want to prevent that, use another language. – Jonas Wilms Mar 04 '19 at 14:33
  • `as you know, in javascript objects and arrays are send by reference`. **No they are not.** Everything in JavaScript is passed by value. See **[this](https://stackoverflow.com/questions/42045586/whats-the-difference-between-a-boolean-as-primitive-and-a-boolean-as-property-o/42045636#42045636)** for details. – Scott Marcus Mar 04 '19 at 14:34
  • 2
    @scott I don't think that it helps anyone if that gets discussed again. Fact is: objects are passed differently than primitives, calling that "by reference" is quite fitting IMO – Jonas Wilms Mar 04 '19 at 14:35
  • @JonasWilms Objects really aren't passed any differently and that's the point. Calling it *by reference* is just wrong. What's stored in the variable is different for objects than primitives. So, to help curb this often repeated incorrect statement, I've chimed in. But, this is why i posted it as a comment, because that's what comments are for, to comment. – Scott Marcus Mar 04 '19 at 14:36
  • Regardless whether the object is passed by reference or not (technically, it's not), to avoid the issue you can either **freeze** the object, either making a **deep copy** of it, using `JSON.parse(JSON.stringify(object));`. There is no other solution, since with any object you pass the memory location of the object iself. Just for the sake of understanding, what is the expected behavior? It's usually the intended behavior to **alter** an object if you pass it to a function. – briosheje Mar 04 '19 at 14:56

1 Answers1

6

You can use a copy of your object or your array:

Object

const copy = JSON.parse(JSON.stringify(obj))

Array

const copy = array.slice(0)
Aziz.G
  • 3,599
  • 2
  • 17
  • 35