In this tutorial, you’ll learn how to pass an object by value. Can you ?

Well, actually you can’t pass an object by value in JavaScript. In this tutorial, you’ll learn how to fix the after effects of passing an object by reference in JavaScript.

The Issue About Passing Object By Reference

Let’s have a look at the code example :

function makeAPICall(obj){
  obj['name'] = "hari";
  console.log('Obect in API call ', obj);
  // make an API call with obj as params
}

function doTask(){
  let mainObj = {'status' : 'new' };
  console.log('Object before API call ', mainObj);
  makeAPICall(mainObj);
  console.log('Object after API call ', mainObj);
}

doTask()

The output of the above code is:

"Object before API call "
[object Object] {
  status: "new"
}
"Obect in API call "
[object Object] {
  name: "hari",
  status: "new"
}
"Object after API call "
[object Object] {
  name: "hari",
  status: "new"
}

As you can see the object passed to the JavaScript method gets modified inside the method makeAPICall. But the change persists in the object mainObj inside doTask method. This is because the object mainObj is passed by reference.

You fix this using a couple of ways :

Using Object.assign

Use Object.assign to assign the passed in object to a target array and return the target array. Here is how it looks:

function makeAPICall(obj){
  let ob = Object.assign({}, obj);
  ob['name'] = "hari";
  console.log('Obect in API call ', ob);
  // make an API call with obj as params
}

function doTask(){
  let mainObj = {'status' : 'new' };
  console.log('Object before API call ', mainObj);
  makeAPICall(mainObj);
  console.log('Object after API call ', mainObj);
}

doTask()

Using Spread Operator

You can use the spread operator to create a copy of the passed in parameter object. Here is how the code looks:

function makeAPICall(obj){
  let ob = { ...obj };
  ob['name'] = "hari";
  console.log('Obect in API call ', ob);
  //make an API call with obj as params
}

function doTask(){
  let mainObj = {'status' : 'new' };
  console.log('Object before API call ', mainObj);
  makeAPICall(mainObj);
  console.log('Object after API call ', mainObj);
}

doTask()