Page 1 of 1

JavaScript question

Posted: Thu Jan 31, 2019 10:23 am
by hgm
Am I correct in assuming that every variable in JavaScript holds merely a pointer to an independently existing object? E.g. if 'moves' is an array, and I would do

var savedMoves = moves;
moves = [];
... // assign something to the elements move[n]
moves = savedMoves;

that I would have my original array of moves back unmodied, and that the operation savedMoves = moves is just a simple assignment of a pointer, rather than actual copying of the entire array?

Re: JavaScript question

Posted: Thu Jan 31, 2019 10:53 am
by Henk
Don't know much about javascript. Array is an object so it would be logical to copy only the reference.

Re: JavaScript question

Posted: Thu Jan 31, 2019 1:22 pm
by nionita
Yes, for arrays this is true, you just copy a reference. For primitive type you would copy the value itself.

Re: JavaScript question

Posted: Thu Jan 31, 2019 3:41 pm
by jdart
arr1 = arr2.slice(0)

copies arr2 to arr1 by value (but caution: if the array elements have complex types those are still copied by reference).

--Jon

Re: JavaScript question

Posted: Thu Jan 31, 2019 4:09 pm
by Henk
jdart wrote: Thu Jan 31, 2019 3:41 pm arr1 = arr2.slice(0)

copies arr2 to arr1 by value (but caution: if the array elements have complex types those are still copied by reference).

--Jon
They call that shallow copy. Otherwise deep copy.