1

I'm cloning a variable for manipulation in one of my functions, and I'm NOT reassigning it back. Why is the second console.log() printing the below?

img1

Here is the code:

console.log('BEFORE -> ', JSON.parse(JSON.stringify(vm.referenceMatrix)));

var referenceId = null;

var referenceMatrix = vm.referenceMatrix;

for (var i = 0; i < length; i++) {
    referenceId = references[i].article_reference_id;

    referenceMatrix[referenceId] = i + 1;
}

console.log('AFTER -> ', JSON.parse(JSON.stringify(vm.referenceMatrix)));

//vm.referenceMatrix = referenceMatrix;

As you can see, vm.referenceMatrix = referenceMatrix; is commented out, so how it this possible?

Edit:

This code generates the same output as in the image above:

console.log('BEFORE -> ', JSON.parse(JSON.stringify(vm.referenceMatrix)));

var referenceId = null;

var referenceMatrixs = vm.referenceMatrix;

for (var i = 0; i < length; i++) {
    referenceId = references[i].article_reference_id;

    referenceMatrixs[referenceId] = i + 1;
}

console.log('AFTER -> ', JSON.parse(JSON.stringify(vm.referenceMatrix)));

//vm.referenceMatrix = referenceMatrix;
Mike K
  • 7,621
  • 14
  • 60
  • 120

2 Answers2

3

Perhaps you come from a different language, but in JavaScript - each assignment is by reference. That means that:

const x = { value: 1};
const y = x;
y.value = 2;
console.log(x); // { value: 2 }

Because the object is not cloned, and the reference is shared between the too variables. If you want to deep copy the variables ("copy by value", like in C++), there are a lot of ways to do that (What is the most efficient way to deep clone an object in JavaScript?)

Shachar Har-Shuv
  • 666
  • 6
  • 24
1

I'm cloning a variable for manipulation in one of my functions

I think you mean this line of code:

var referenceMatrixs = vm.referenceMatrix;

This does not clone anything. Instead it assigns a reference to the object. All changes to referenceMatrixs will also be seen in vm.referenceMatrix.

Note that your output statements do clone the object:

console.log('BEFORE -> ', JSON.parse(JSON.stringify(vm.referenceMatrix)));

However, the clone is only used for output and immediately thrown away. This is a lot of code for basically no purpose. You will get the exact same result with

    console.log('BEFORE -> ', vm.referenceMatrix);

Since this statement does not modify the object, there is no reason to clone here.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Coming from C++.. where we explicitly state if we're copying by reference or by value. It's funny though, I've been working with Javascript nearly equally as long as with other languages. Haven't encountered this specific problem. Guess you learn something new every day. Thanks. – Mike K May 03 '19 at 16:46
  • @MikeK Just keep in mind that lists and objects are always references in JavaScript. – Code-Apprentice May 03 '19 at 17:37