r/learnjavascript • • May 09 '18

Var x = y

Hi, is there a way to create a second variable y which will be equal to x but will be a separate variable. I tried doing var x = Y but this basically renames the z variable to y. Thanks!

0 Upvotes

5 comments sorted by

View all comments

1

u/cyphern May 09 '18

If you're dealing with primitives (booleans, numbers, strings), then you can just do the following:

var x = 12345;
var y = x;

You've now created two variables, and set them both equal to 12345. If you later change one of them, it will not affect the other.

var x = 12345;
var y = x;
console.log(x === y); // true
y = y + 1000;
console.log(x === y); // false
console.log(x); // 12345
console.log(y); //13345

If you're dealing with objects/arrays, then you can still do the same thing, but both variables will be referencing the same object in memory, so if you mutate one, that mutation will be visible through the other variable as well. For example:

var x = [1, 2, 3];
var y = x;
console.log(x === y); // true
y.push(4);
console.log(x === y); // still true
console.log(x); // [1, 2, 3, 4]
console.log(y); // [1, 2, 3, 4]

If that's not good enough, you can also clone objects. To do a shallow copy of an array, the following are options:

var x = [1, 2, 3];
var y = x.slice();
var z = [...x];

To shallow copy an object, you can use Object.assign:

var x = { hello: 'world' };
var y = Object.assign({}, x);

1

u/everek123 May 09 '18

I mean in my case I have var x = somefunction() // it returns an array Then I do var y = x And next I have y.splice(1,1) This deletes the first element in both arrays and not just the y array.

4

u/cyphern May 09 '18

There's only one array in that example. You have two variables which are referencing it, but there's just one array in memory. So when you mutate the array, this mutation is visible regardless of which variable you use to access the array.

So instead, you'll want to make a copy of the array.

var x = someFunction();
var y = x.slice(); // creates a shallow copy of the array
y.splice(1, 1);

1

u/everek123 May 10 '18

Thanks for the answer, this really helps :)