sonam
sonam

Reputation: 3770

Pass by reference and value in javascript / jquery

I have a test case as below:

$(document).ready(function() {
   var arrayList=[{"name":"pradip"},{"name":"Tengi"}];
   var del = function(list) {
      list.splice(1,1);
      $("div").append("function:" + list.length +"<br>"); 
   };
   $("div").append("original:" + arrayList.length+"<br>");
   del(arrayList);
   $("div").append("modified"+ arrayList.length+"<br>");

   var test=1;
   var increase=function(a){
      a++;
      $("div").append("function="+a+"<br>");
   }
   $("div").append("original test="+test+"<br>");
   increase(test);
   $("div").append("increased test="+test+"<br>"); 
});

The output is :

original:2
function:1
modified1
original test=1
function=2
increased test=1

When I pass array to a function by value, and in the function I change the value, the change is also reflected in the original array but in other case, there is no change.

JSFiddle

Why is the pass by value acting as if it is pass by reference for array ?

Upvotes: 0

Views: 4658

Answers (2)

ismnoiet
ismnoiet

Reputation: 4169

if the passed argument is a primitive type like (string ,number) then a copy of the passed parameter is created (destroyed when the function call is finished) which means passage by value

but if the passed argument is an object or an array then we have passage by reference

here is an example

num = 10;
str = 'string';
arr = [1,2,3]
obj = {p1:'val1'}

function passedBy(arg1){
  if(typeof arg1 === 'object'){
    // we are in the case where arg1 can be an object or an array 
       if(arg1.constructor === Array){
          // add 1 to the passed array 
          arg1.push(1);
       }else{
           // add p2 property to the passed object
           arg1.p2 = 'val2';

      }

  }else{
      //here arg1 parameter is a string or a number
      // if arg1 is a string the following instruction should perform a concatenation     
      // operation instead it should add 1 to arg1
      arg1 +=1 
  }

}

now you can try this simple function to see the difference between passage by reference and passage by value

for example

passedBy(num);  
passedBy(str); 
console.log(num);
console.log(str);

we can see easily that the value of str and num is not changed even though we modified them inside the passedBy() function

BUT IF WE TRY

passedBy(arr);
passedBy(obj);
console.log(arr);
console.log(obj);

we can see clearly that the content of arr and obj in not the same as the initial one

HOPE YOU GET IT

Upvotes: -1

SLaks
SLaks

Reputation: 888067

You're passing a reference to the array by value.

You now have two references to the same array instance.

If you don't want the array to change, you need to explicitly create a copy .

Upvotes: 2

Related Questions