JavaScript question

Discussion of chess software programming and technical issues.

Moderators: hgm, Rebel, chrisw

User avatar
hgm
Posts: 27788
Joined: Fri Mar 10, 2006 10:06 am
Location: Amsterdam
Full name: H G Muller

JavaScript question

Post 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?
Henk
Posts: 7216
Joined: Mon May 27, 2013 10:31 am

Re: JavaScript question

Post by Henk »

Don't know much about javascript. Array is an object so it would be logical to copy only the reference.
nionita
Posts: 175
Joined: Fri Oct 22, 2010 9:47 pm
Location: Austria

Re: JavaScript question

Post by nionita »

Yes, for arrays this is true, you just copy a reference. For primitive type you would copy the value itself.
jdart
Posts: 4366
Joined: Fri Mar 10, 2006 5:23 am
Location: http://www.arasanchess.org

Re: JavaScript question

Post 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
Henk
Posts: 7216
Joined: Mon May 27, 2013 10:31 am

Re: JavaScript question

Post 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.