0

While working with queue in node.js, I found a different behaviour of the variable passed as a parameter to function and local variable. I assign the value of variable passed as a parameter in a function to local variable after which when I perform any operation on local variable, the value of both variable also gets changed to the new value. While the value of variable passed as parameter to the function should never change until I assign a new value to it.

To dig more deep about this behaviour, I used two local variables and still the same output was found

Here is the example code of the issue:

var change_value = function (payload) {
    let value = payload;
    console.log('payload:', payload, '\nvalue:', value);
    value.color = 'black';
    console.log('payload:', payload, '\nvalue:', value);
    let new_value = value;
    console.log('payload:', payload, '\nvalue:', value, '\nnew_value:', new_value);
    delete new_value.color;
    console.log('payload:', payload, '\nvalue:', value, '\nnew_value:', new_value);
}

change_value({
    name: 'devil'
})

The output of the above code is :

payload: { name: 'devil' } 
value: { name: 'devil' }

payload: { name: 'devil', color: 'black' } 
value: { name: 'devil', color: 'black' }

payload: { name: 'devil', color: 'black' } 
value: { name: 'devil', color: 'black' } 
new_value: { name: 'devil', color: 'black' }

payload: { name: 'devil' } 
value: { name: 'devil' } 
new_value: { name: 'devil' }

While the output I want/am expecting is :

payload: { name: 'devil' } 
value: { name: 'devil' }

payload: { name: 'devil'} 
value: { name: 'devil', color: 'black' }

payload: { name: 'devil'} 
value: { name: 'devil', color: 'black' } 
new_value: { name: 'devil', color: 'black' }

payload: { name: 'devil' } 
value: { name: 'devil', color: 'black' } 
new_value: { name: 'devil' }
Gaurav
  • 103
  • 1
  • 11
  • Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – CertainPerformance May 22 '19 at 07:32
  • You only have one object in memory there. `payload === value`, you just have two variables that point to the same object in memory. If you want to clone the object, you need to do so explicitly – CertainPerformance May 22 '19 at 07:33
  • @CertainPerformance how you please help me how to do it explicitly. – Gaurav May 22 '19 at 07:39
  • Look for `How to clone object javascript` – CertainPerformance May 22 '19 at 07:40
  • @CertainPerformance, thanks man, by inspecting the output I understood that it was referring to same object in memory but I was not aware why it was happening. So, as per my use case, I referred this [https://stackoverflow.com/questions/6089058/nodejs-how-to-clone-an-object/12826757] and now have resolved the issue. Thanks once again. – Gaurav May 22 '19 at 07:46

0 Answers0