1

I'm having an issue with saving a variable value at a certain time in javascript. At a basic level, in the code below, I would like variable 'b' to keep the value it was assigned

var a = [];
var b = '';
var c = 'value';

a.push(c);
b = a;
console.log(b); // b = ["value"]
a.push(c);
console.log(b); // b = ["value", "value"], but i want it to be just ["value"]

I've seen various solutions to similar problems using closures such as in this question: Intentionally "freezing" a javascript variable using a self-executing function. I have tried that solution unsuccessfully in this Jsbin: http://jsbin.com/zusara/1/edit?js,console.

Any help would be greatly appreciated. Thanks and best!

Community
  • 1
  • 1
  • 1
    Is this question specifically about arrays? – Felix Kling Nov 10 '14 at 19:55
  • In this specific case try `b = a.slice()`. – dfsq Nov 10 '14 at 19:55
  • Problem is they are pointers pointing to the same object a and b both point to the same object... – brso05 Nov 10 '14 at 20:00
  • Ah thank you for the clarification. This specific example is about arrays, but i was hoping to use the solution on objects later on – user1177142 Nov 10 '14 at 20:01
  • Possible duplicate of [Javascript fastest way to duplicate an Array - slice vs for loop](https://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop) – Eduard Aug 30 '18 at 11:57

2 Answers2

3

Assigning an array to a variable does NOT make a copy. Thus both a and b variables then point to the same array and any change made via either variable will show up in the other.

If you want a copy of an array in Javascript, then you have to explicitly make a copy of the array.

var a = [];
var c = 'value';
a.push(c);
// make shallow copy of a into b
var b = a.slice(0);

b now contains a completely separate array and modifications of a will not affect b.

Note: this is a shallow copy, not a deep copy and is the solution for arrays. A shallow copy doesn't not copy objects in the array or objects in those objects. Making a deep copy requires substantially more code, but is often not required and does not appear to be required in your case for the example you provided.


If you want a deep copy and want to include objects too, not just arrays (I provided the simple solution for a shallow copy of an array), you can see this reference there are plenty of options and debate here:

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    note that this pattern won't "freeze" objects or sub-arrays in the array, and so the copied array's values could change later if it contains non-primitive elements. you can do the ugly+slow but effective (for many types) arr2=JSON.parse(JSON.stringify(arr)) to get a deep copy. – dandavis Nov 10 '14 at 20:00
  • 1
    @dandavis = yes, that's why the comment in the code says "shallow" copy. Making a "deep" copy that will also clone any objects in the array and any objects in those objects requires substantially more code, but fortunately is often not required. – jfriend00 Nov 10 '14 at 20:00
  • Good answer, but why limit it to arrays? It does apply to any type. – georg Nov 10 '14 at 20:02
  • thanks, jfriend and dandavis. dandavis - do you know what i would need to do in order to freeze objects? or to make an exact copy and store it in another variable so that it won't get changed later? – user1177142 Nov 10 '14 at 20:03
  • 1
    @georg: the JSON.parse(JSON.stringify(x)) trick works for deep non-custom objects.. – dandavis Nov 10 '14 at 20:03
  • @user1177142 - I provided you with the code in my answer. – jfriend00 Nov 10 '14 at 20:03
  • 2
    @georg - the question was about arrays so I provided the simplest answer that applied to the code the OP asked about. It is not as trivial to copy an object and there are long debates and answers here on SO on the best way to clone entire object hierarchies. If you have self referential structures (one part of the structure has a reference to another part of the structure), it can get quite complicated as you can't use any of the simpler techniques. – jfriend00 Nov 10 '14 at 20:06
  • Thank you all for the comments, this was very informative! – user1177142 Nov 10 '14 at 20:08
  • @georg = I added a reference for cloning a whole object. – jfriend00 Nov 10 '14 at 20:09
1

One way to achieve this is by using the slice function.

Instead of: b = a;

Try using:

b = a.slice();

boxsome
  • 178
  • 5