0

Is there any way I can make a deep copy of a variable? (NOT object). Example:

var a = ["String", "string"];
var b = a;

b.splice(1, 1);

b = a;

In my example, a isnt supposed to change, I want to use it later for restoring b. (As showed in code above).

I understand that = just makes a new reference, hence the question: is there any other way I can make a deep copy instead of a reference?

Want to note that I can't be using any library, I've found answers suggesting jQuery and such, but I cannot use this.

Chaost
  • 137
  • 3
  • 12

1 Answers1

2

Have you tested your code? Numbers and other primitives are copied, not referenced.

var a = 1;
var b = a;
console.log(`a is ${a}`);
console.log(`b is ${b}`);
b++;
console.log(`a is ${a} (no change)`);
console.log(`b is ${b}`);

After your edit with a different example:

var a = ["foo", "bar"];
var b = a.slice(); // array copy
console.log(`a is ${a}`);
console.log(`b is ${b}`);
b.splice(1, 1);
console.log(`a is ${a} (not changed)`);
console.log(`b is ${b}`);
b = a;
Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34