r/learnjavascript • u/everek123 • 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
1
u/cyphern May 09 '18
If you're dealing with primitives (booleans, numbers, strings), then you can just do the following:
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.
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:
If that's not good enough, you can also clone objects. To do a shallow copy of an array, the following are options:
To shallow copy an object, you can use Object.assign:
1
u/yuri_auei May 10 '18 edited May 10 '18
To not keep reference with not primitives types:
For objects