JavaScript question

Discussion of chess software programming and technical issues.

Moderators: bob, hgm, Harvey Williamson

Forum rules
This textbox is used to restore diagrams posted with the [d] tag before the upgrade.
Post Reply
User avatar
hgm
Posts: 23785
Joined: Fri Mar 10, 2006 9:06 am
Location: Amsterdam
Full name: H G Muller
Contact:

JavaScript question

Post by hgm » Thu Jan 31, 2019 9:23 am

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?

Henk
Posts: 5833
Joined: Mon May 27, 2013 8:31 am

Re: JavaScript question

Post by Henk » Thu Jan 31, 2019 9:53 am

Don't know much about javascript. Array is an object so it would be logical to copy only the reference.

nionita
Posts: 161
Joined: Fri Oct 22, 2010 7:47 pm
Location: Austria

Re: JavaScript question

Post by nionita » Thu Jan 31, 2019 12:22 pm

Yes, for arrays this is true, you just copy a reference. For primitive type you would copy the value itself.

jdart
Posts: 3842
Joined: Fri Mar 10, 2006 4:23 am
Location: http://www.arasanchess.org

Re: JavaScript question

Post by jdart » Thu Jan 31, 2019 2: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

Henk
Posts: 5833
Joined: Mon May 27, 2013 8:31 am

Re: JavaScript question

Post by Henk » Thu Jan 31, 2019 3:09 pm

jdart wrote:
Thu Jan 31, 2019 2: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.

Post Reply