Search code examples
javascriptparameter-passingpass-by-reference

prevent object and arrays modification in javascript


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 !??!


Solution

  • 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)