Alright stackoverflow,
I’ve been working hours on solving an issue in javascript (writing in NodeJS server) but I really don’t get it.
This is what happens:
var data = {x: 50};
var temp = data;
temp.x = 100;
console.log(data.x);
//logs 100
I have tested this exact code and it really shows 100.
My question:
How do I clone a var to a temp one and change the temp var without the original changing along.
You’ll have to clone the original object. This is because storing the object in another variable doesn’t create a new object with the same properties as the previous one; it just creates a reference to the same object. Sadly, there aren’t any built in solutions to get around this, but there are a few solutions. Here some that come to mind:
Or:
Not to be self-promoting, but I’ve written up a blog post about this subject which goes into a little more detail. You can find here.